__bases__ 不起作用!接下来是什么?
以下代码在 Python 3.x 中不起作用,但它曾经适用于旧式类:
class Extender:
def extension(self):
print("Some work...")
class Base:
pass
Base.__bases__ += (Extender,)
Base().extension()
问题很简单: 如何动态(在运行时)添加超类Python 3.x 中的类?
但我已经准备好答案将是困难的! )
The following code doesn't work in Python 3.x, but it used to work with old-style classes:
class Extender:
def extension(self):
print("Some work...")
class Base:
pass
Base.__bases__ += (Extender,)
Base().extension()
Question is simple: How can I add dynamically (at runtime) a super class to a class in Python 3.x?
But I'm ready the answer will be hard! )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来可以动态更改
Base.__bases__
如果
Base.__base__
不是object
。 (动态更改是指从Base
继承的所有预先存在的实例也会动态更改。否则请参阅 Mykola Kharechko 的解决方案)。如果
Base.__base__
是某个虚拟类TopBase
,那么对Base.__bases__
的赋值似乎可以工作:经过测试,可以在 Python 2 中工作(对于新式和旧式类)和Python 3。我不知道为什么它可以工作,而这却不能:
It appears that it is possible to dynamically change
Base.__bases__
if
Base.__base__
is notobject
. (By dynamically change, I mean in such a way that all pre-existing instances that inherit fromBase
also get dynamically changed. Otherwise see Mykola Kharechko's solution).If
Base.__base__
is some dummy classTopBase
, then assignment toBase.__bases__
seems to work:This was tested to work in Python 2 (for new- and old-style classes) and for Python 3. I have no idea why it works while this does not:
对于我来说这是不可能的。但您可以动态创建新类:
As for me it is impossible. But you can create new class dynamically: