Python多重继承:动态进行操作有什么问题? [英] Python multiple inheritance: Whats wrong doing it dynamically?
本文介绍了Python多重继承:动态进行操作有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基于此答案,__new__
和__init__
应该如何在Python中工作,
Based on this answer, of how __new__
and __init__
are supposed to work in Python,
我编写了这段代码来动态定义和创建新的类和对象.
I wrote this code to dynamically define and create a new class and object.
class A(object):
def __new__(cls):
class C(cls, B):
pass
self = C()
return self
def foo(self):
print 'foo'
class B(object):
def bar(self):
print 'bar'
a = A()
a.foo()
a.bar()
基本上,因为A的__new__
返回继承了A和B的动态创建的C,所以它应该具有属性bar
.
Basically, because the __new__
of A returns a dynamically created C that inherits A and B, it should have an attribute bar
.
为什么C
没有具有bar
属性?
推荐答案
解决无限递归:>
Resolve the infinite recursion:
class A(object):
def __new__(cls):
class C(cls, B):
pass
self = object.__new__(C)
return self
(感谢 balpha 用于指出实际问题.)
(Thanks to balpha for pointing out the actual question.)
这篇关于Python多重继承:动态进行操作有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文