以下代码显示了在类范围内使用全局变量。
class Foo(object): bar = 2 foo = Foo()print Foo.bar, print foo.bar, # setting foo.bar would not change class attribute bar # but will create it in the instance foo.bar = 3 print Foo.bar, print foo.bar, # to change class attribute access it via class Foo.bar = 4 print Foo.bar, print foo.bar
输出结果
2 2 2 3 4 3