Q: I have two files, the first is this:
File b.py:
-------------------
from a import cla_a
class cla_b(cla_a): pass
-------------------
File a.py
-------------------
class cla_a(object): pass
class cla_c(cla_a): pass
if __name__ == "__main__":
import b as mod
print issubclass(mod.cla_b, cla_a)
print issubclass(mod.cla_b, mod.cla_a)
print issubclass(cla_c, cla_a)
print mod.cla_a is cla_a
-------------------
Results of 'python a.py'
False
True
True
False
A: Your file 'a.py' is two things. It's the code being used
as the "__main__" module *and* it's used as the "a" module.
Add this to your a.py:__main__ to see the difference.
import sys
main_module = sys.modules["__main__"]
print "main is from", main_module.__file__
a_module = sys.modules["a"]
print "a is from", a_module.__file__
print "Are the modules the same?", a_module == main_module
print "Are the classes the same?", a_module.cla_a ==
main_module.cla_a
You'll see that the file a.py is used twice, and the
class cla_a defined once as __main__.cla_a and the other
as a.cla_a .
To make what you want work, well, a good rule is to avoid
circular imports. Another is that your main code should
not be imported. But if you want so see your code to work
as you expect it to work, you need to change b.py so that
the "from a import cla_a" is instead
"from __main__ import cla_a"
阅读(816) | 评论(0) | 转发(0) |