__base__不起作用!下一步是什么? [英] __bases__ doesn't work! What's next?
问题描述
以下代码在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()
问题很简单: 如何在运行时动态地将超类添加到Python 3.x中的类?
但是我已经准备好答案了! )
But I'm ready the answer will be hard! )
推荐答案
似乎可以动态更改Base.__bases__
如果Base.__base__
不是object
. (通过动态更改,我的意思是,从Base
继承的所有现有实例也将动态更改.否则,请参见
It appears that it is possible to dynamically change Base.__bases__
if Base.__base__
is not object
. (By dynamically change, I mean in such a way that all pre-existing instances that inherit from Base
also get dynamically changed. Otherwise see Mykola Kharechko's solution).
如果Base.__base__
是某个虚拟类TopBase
,则分配给Base.__bases__
似乎可行:
If Base.__base__
is some dummy class TopBase
, then assignment to Base.__bases__
seems to work:
class Extender(object):
def extension(self):
print("Some work...")
class TopBase(object):
pass
class Base(TopBase):
pass
b=Base()
print(Base.__bases__)
# (<class '__main__.TopBase'>,)
Base.__bases__ += (Extender,)
print(Base.__bases__)
# (<class '__main__.TopBase'>, <class '__main__.Extender'>)
Base().extension()
# Some work...
b.extension()
# Some work...
Base.__bases__ = (Extender, TopBase)
print(Base.__bases__)
# (<class '__main__.Extender'>, <class '__main__.TopBase'>)
Base().extension()
# Some work...
b.extension()
# Some work...
经过测试可以在Python 2(适用于新旧类)和Python 3中运行.我不知道为什么它可以运行,而不能运行:
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:
class Extender(object):
def extension(self):
print("Some work...")
class Base(object):
pass
Base.__bases__ = (Extender, object)
# TypeError: __bases__ assignment: 'Extender' deallocator differs from 'object'
这篇关于__base__不起作用!下一步是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!