只是为了跟进AlexMartelli和Catskul的答案,有些真正简单但令人讨厌的案例似乎令人困惑reload
至少在Python 2中,。
假设我有以下源代码树:
- foo
- __init__.py
- bar.py
具有以下内容:
init.py:
from bar import Bar, Quux
bar.py:
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
堂课与自己不同步,这很奇怪。
... possible ... import a component Y from module X
” vs“question is ... importing a class or function X from a module Y
”。我为此添加了一个编辑。