class test(object):
class_var=5
def __init__(self):
self.abc=9
obj=test()
print("Instance Variable")
print obj.abc()
print("Class Variable")
print test.class_var()
print("Class variable through Instance Variable")
print obj.class_var()
test.class_var=99
print("After Changing")
print("Class Variable")
print test.class_var()
print("Class variable through Instance Variable")
print obj.class_var()
我对python比较陌生,我检查了类变量和实例变量在python中的工作方式,以及它们与java和c++中的静态变量的相似性。我试着执行这段代码,却得到了这个错误
F:\pythont>python static.py Instance Variable Traceback (most recent call last): File "static.py", line 8, in print obj.abc() TypeError: 'int' object is not callable
F:\pythont>
我很困惑,因为我很确定在python中不需要使用getter就可以访问变量。因为当我直接访问
如错误消息所示,
obj.abc
是一个整数。当您在它后面加上括号时,您试图调用它,但不能调用整数。在要读取变量值,只需使用
obj.abc
,不带括号。在相关问题 更多 >
编程相关推荐