只是跟进AlexMartelli's和Catskul's答案,还有一些出现混淆reload
,至少在Python 2
很简单,但讨厌的情况下,假设我有以下源代码树:
- foo
- __init__.py
- bar.py
具有以下内容:
init.py:
from bar import Bar, Quux
吧。潘岳:
print "Loading bar"
class Bar(object):
@property
def x(self):
return 42
class Quux(Bar):
object_count = 0
def __init__(self):
self.count = self.object_count
self.__class__.object_count += 1
@property
def x(self):
return super(Quux,self).x + 1
def __repr__(self):
return 'Quux[%d, x=%d]' % (self.count, self.x)
这一切正常,而无需使用reload
:
>>> from foo import Quux
Loading bar
>>> Quux()
Quux[0, x=43]
>>> Quux()
Quux[1, x=43]
>>> Quux()
Quux[2, x=43]
但尝试重新加载,它要么没有效果或破坏的东西:
>>> import foo
Loading bar
>>> from foo import Quux
>>> Quux()
Quux[0, x=43]
>>> Quux()
Quux[1, x=43]
>>> reload(foo)
<module 'foo' from 'foo\__init__.pyc'>
>>> Quux()
Quux[2, x=43]
>>> from foo import Quux
>>> Quux()
Quux[3, x=43]
>>> reload(foo.bar)
Loading bar
<module 'foo.bar' from 'foo\bar.pyc'>
>>> Quux()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "foo\bar.py", line 17, in __repr__
return 'Quux[%d, x=%d]' % (self.count, self.x)
File "foo\bar.py", line 15, in x
return super(Quux,self).x + 1
TypeError: super(type, obj): obj must be an instance or subtype of type
>>> Quux().count
5
>>> Quux().count
6
>>> Quux = foo.bar.Quux
>>> Quux()
Quux[0, x=43]
>>> foo.Quux()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "foo\bar.py", line 17, in __repr__
return 'Quux[%d, x=%d]' % (self.count, self.x)
File "foo\bar.py", line 15, in x
return super(Quux,self).x + 1
TypeError: super(type, obj): obj must be an instance or subtype of type
>>> foo.Quux().count
8
只有我能方式确保bar
子模块重新加载到reload(foo.bar)
;我访问重新加载Quux
类的唯一方法是到达并从重新加载的子模块中抓取;但foo
模块自身保持保持到原始Quux
类对象,大概是因为它使用from bar import Bar, Quux
(而不是import bar
随后Quux = bar.Quux
);此外,Quux
类与它本身不同步,这是奇怪的。
我相信,在这个问题上的矛盾:“'... ...可能从导入模块X'分量Y”与“'问题是......从一个模块Y'导入类或函数X ”。我为此添加了一个编辑。 – Catskul
似乎标记的答案实际上并没有回答这个问题,我相信我的答案。你能更新/评论吗? – Catskul