class Test:
num1 = 1
# CASE 1
# WHY GLOBAL HERE? But no global below in CASE 2
global num2
num2 = 2
def printNum2(self):
return num2
## FAILURE WITH NON-GLOBAL num2, why?
# should print 2, with instance
i = Test()
print i.printNum2()
# CASE 2
#
#AUTOMATICALLY GLOBAL SCOPE?
num1=1
def print1():
return num1
print print1()
最佳答案
您不需要全局来使 printNum2
正常工作。相反,使用这个:
class Test:
num1 = 1
num2 = 2
def printNum2(self):
return self.num2
如果您想执行以下操作,则只需要全局:
x = Test()
print num2
//instead of
print x.num2
关于python - 为什么类方法访问它的类变量中需要 `global var`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5396983/