【发布时间】:2018-04-16 15:07:48
【问题描述】:
我发现reload()(Python 2 内置和来自importlib)的一个令人讨厌的行为,我正试图绕过它。
我正在交互式 Python 解释器中分析数据。我的代码组织在模块中(兼容 Python 2 和 3),我经常更改这些模块。
由于加载数据时间长,重启解释器不可行,所以我更喜欢递归地重新加载模块。
问题在于reload() updates the code but preserves the module global scope(它也适用于Python 3 importlib.reload())。使用super() 的方法似乎有害(我花了一段时间才意识到发生了什么)。
模块 bar.py 的最小失败示例:
class Bar(object):
def __init__(self):
super(Bar, self).__init__()
是:
>>> import bar
>>> class Foo(bar.Bar):
... pass
...
>>> reload(bar)
<module 'bar' from '[censored]/bar.py'>
>>> Foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "[censored]/bar.py", line 3, in __init__
super(Bar, self).__init__()
TypeError: super(type, obj): obj must be an instance or subtype of type
我可以:
-
use
super()without arguments in Python 3 manner(不是 兼容 Python 2), - 放弃它并改为致电
Bar.__init__(self)(which is harder to maintain 和discouraged), - monkey-patch 类添加包含循环的类属性 引用类本身。
没有我喜欢的想法。有没有其他办法处理这个问题?
【问题讨论】:
-
您的
bar.py已经失败,因为您将super(Bar, self).__init__()放在类级别而不是__init__方法中。 -
您对
super的使用实际上是无效的。super用于不在类主体中的类的方法中。 -
另外,一般来说,重新加载模块真的很难做到,
reload只处理最简单的情况。最好的选择永远是从头开始重新启动 Python。 -
糟糕,我在输入示例时漏掉了一行。
-
@bphi:永远不要这样做,因为一旦您将该类子类化并且
self.__class__是子类,它就会中断。如果就这么简单,super一开始就不会需要类型参数。
标签: python python-2.7 python-3.x python-import python-module