我觉得比平常更笨了,对不起。有人能帮我摆脱痛苦,解释一下为什么__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”被声明为类级变量。它类似于JAVA中的静态变量。变量“s”将由类C的所有实例共享。因此,也可以使用类名(在本例中为C)访问它。你知道吗
您需要使用
self
或类名来访问类变量s
相关问题 更多 >
编程相关推荐