【问题标题】:Python init doesn't see class variablePython init 看不到类变量
【发布时间】:2018-11-24 21:59:42
【问题描述】:

我感觉比平时更笨了,抱歉。谁能让我摆脱痛苦并解释为什么__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

【问题讨论】:

标签: python class scope visibility


【解决方案1】:

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

class C:
    s = "but why"

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


if __name__ == '__main__':

    c = C()

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-02
      • 2012-07-04
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      • 2019-01-31
      • 2021-11-03
      • 1970-01-01
      相关资源
      最近更新 更多