1 # foo.py 2 a = 3 3 4 5 class Foo(object): 6 # noinspection PyMethodMayBeStatic 7 def __init__(self): 8 pass 9 10 def f(self): 11 global a 12 a = 4 13 print(a)
1 # bar.py 2 from foo import Foo 3 4 5 class Test(Foo): 6 # noinspection PyMethodMayBeStatic 7 def __init__(self): 8 global a 9 super(Test, self).__init__() 10 self.f() 11 a = 5 12 self.f() 13 print(Foo.f.__globals__['a']) 14 15 16 Test()
# 4
# 4
# 4
可以看出输出4,4, 4,说明bar.py虽然声明了global a, 但并没有改变foo.py的global a, 原因为bar.py 中 声明global a作用域只是在当前模块,若将barl.py中的a = 5赋值语句注释掉,
将会报错,变量未声明。
正确使用方法如下:
1 # bar.py 2 from foo import Foo 3 4 5 class Test(Foo): 6 # noinspection PyMethodMayBeStatic 7 def __init__(self): 8 super(Test, self).__init__() 9 self.f() 10 print(Foo.f.__globals__['a']) 11 12 Test()