Python多重继承:__new__要调用哪些?

时间:2010-01-26 02:18:39

标签: python new-operator multiple-inheritance class-hierarchy

我有一个班级Parent。我想为__new__定义一个Parent,以便在实例化时做一些魔术(为什么,请参阅脚注)。我也希望子类继承这个和其他类来获得Parent的功能。 Parent的{​​{1}}将返回子类的基类和__new__类的子类的实例。

这就是如何定义子类:

Parent

但现在我不知道在class Child(Parent, list): pass 的{​​{1}}中要拨打__new__的内容。如果我致电Parent,则上述__new__示例会抱怨应调用object.__new__。但Child怎么会知道呢?我让它工作,所以它遍历所有list.__new__,并在Parent块内调用每个__bases__

__new__

但这看起来像个黑客。当然,必须有更好的方法来做到这一点吗?

感谢。

  • 我想使用try:的原因是我可以返回一个子类的对象,该子类具有分配给该类的一些动态属性(魔术class Parent(object): def __new__(cls, *args, **kwargs): # There is a special wrapper function for instantiating instances of children # classes that passes in a 'bases' argument, which is the __bases__ of the # Children class. bases = kwargs.get('bases') if bases: cls = type('name', bases + (cls,), kwargs.get('attr', {})) for base in cls.__mro__: if base not in (cls, MyMainType): try: obj = base.__new__(cls) break except TypeError: pass return obj return object.__new__(cls) 属性等)。我could have done this in __init__,但如果新类具有不同的内部结构,我将无法在__new__中修改__int__,这是由于多重继承所致。

1 个答案:

答案 0 :(得分:4)

我认为这会让你得到你想要的东西:

return super(Parent, cls).__new__(cls, *args, **kwargs)

,您不需要bases关键字参数。除非我弄错了你并且故意把它放在那里。

相关问题