在python中以编程方式向类添加继承?

2024-10-03 06:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我能让一个类继承Python中的类吗?在

到目前为止,我得到的是:

base = list(cls.__bases__)
base.insert(0, ClassToAdd )
base = tuple( base )
cls = type( cls.__name__, base, dict(cls.__dict__) )

Tags: namebasetypedictlistclsinsertbases
3条回答

下面是一个例子,使用Greg Hewgill的建议:

class Foo(object):
    def beep(self):
        print('Hi')

class Bar(object):
    x=1  

bar=Bar()
# bar.beep()
# AttributeError: 'Bar' object has no attribute 'beep'

Bar=type('Bar',(Foo,object),Bar.__dict__.copy())
bar.__class__=Bar
bar.beep()
# Hi

另一个选择不是动态更改类层次结构,而是用新功能装饰对象实例。这通常更干净、更易于调试,因为您只更改代码在控件中的对象,而不必对整个类层次结构进行横切更改。在

def extend_object(obj):
    class ExtensionClass(obj.__class__):
        def new_functionality(self):
             print "here"
    obj.__class__ = ExtensionClass

b = Foo()
extend_object(b)
b.new_functionality()
#prints "here"

是的,^{}内置函数有一个三参数形式,可以执行以下操作:

type(name, bases, dict)

Return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute.

相关问题 更多 >