【发布时间】: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
【问题讨论】:
-
因为 s 没有为 init try print(self.s) 定义
-
您需要使用 self.s - 函数范围没有嵌套在类中。
标签: python class scope visibility