Python init没有看到类变量

时间:2018-06-15 04:26:22

标签: python class scope visibility

我感觉比平常更愚蠢,抱歉。有人可以让我摆脱痛苦并解释为什么__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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

class C:
    s = "but why"

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


if __name__ == '__main__':

    c = C()
相关问题