Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1361307
  • 博文数量: 343
  • 博客积分: 13098
  • 博客等级: 上将
  • 技术积分: 2862
  • 用 户 组: 普通用户
  • 注册时间: 2005-07-06 00:35
文章存档

2012年(131)

2011年(31)

2010年(53)

2009年(23)

2008年(62)

2007年(2)

2006年(36)

2005年(5)

分类: Python/Ruby

2010-12-02 22:35:39

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"
阅读(778) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~