Can anyone explain this case of python static class variable?

I have the following modules:

File a.py

class Foo(object):
  x = 5

if __name__ == '__main__':
  print Foo.x #5
  Foo.x = 7
  print Foo.x #7
  b = __import__('b')
  print b.Bar.x #5

File b.py

from a import Foo

class Bar(Foo):
  pass

File c.py

if __name__ == '__main__':
  import a
  print a.Foo.x #5
  a.Foo.x = 7
  print a.Foo.x #7
  b = __import__('b')
  print b.Bar.x #7

If I run a.py, I get 5,7,5, and if I run b.py, I get 5,7,7. I am not sure what the correct answer should be, but I would expect that they would be agreed.

+4
source share
1 answer

Python creates a separate namespace for the core module sys.modules['__main__']. You check this namespace in a.py:

if __name__ == '__main__'

However, when b.pyused from a import Foo, it creates a new namespace sys.modules['a']. Both of these namespaces have a separate copyFoo .

Foo.x, __main__.Foo.x, b.Bar.x a.Foo.x, .

c.py Foo a, b.Bar c a.Foo .

+6

All Articles