Python init没有看到variab类

2024-04-25 14:35:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我觉得比平常更笨了,对不起。有人能帮我摆脱痛苦,解释一下为什么__init__看不到类变量s?你知道吗

谢谢。你知道吗

class C:
    s = "but why"

    def __init__(self):
        print(s)

c = C()   
#global DEFAULT_STRING = "(undefined)"

错误

Traceback (most recent call last):
    File "/Users/pvdl/Desktop/FH.sp18python/hw/7/test5.py", line 7, in module
    c = C()
    File "/Users/pvdl/Desktop/FH.sp18python/hw/7/test5.py", line 5, in __init__
    print(s)
NameError: name 's' is not defined

Process finished with exit code 1

Tags: inpyinitlineusersclassfilebut
2条回答

“s”被声明为类级变量。它类似于JAVA中的静态变量。变量“s”将由类C的所有实例共享。因此,也可以使用类名(在本例中为C)访问它。你知道吗

您需要使用self或类名来访问类变量s

class C:
    s = "but why"

    def __init__(self):
        print(C.s, self.s)


if __name__ == '__main__':

    c = C()

相关问题 更多 >