简体   繁体   English

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

[英]Adding inheritance to a class programmatically in python?

Can I make a class inherit a class "in-program" in Python?我可以让一个类继承 Python 中的“程序内”类吗?

heres what i have so far:继承人到目前为止我所拥有的:

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

Here is an example, using Greg Hewgill's suggestion:这是一个示例,使用 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'

Yes, the type() built-in function has a three argument form that can do this:是的, type()内置函数有一个可以执行此操作的三参数形式:

type ( name , bases , dict )类型名称基数字典

Return a new type object.返回一个新的类型对象。 This is essentially a dynamic form of the class statement.这本质上是class语句的动态形式。 The name string is the class name and becomes the __name__ attribute; name字符串是类名并成为__name__属性; the bases tuple itemizes the base classes and becomes the __bases__ attribute;元组逐项列出基类并成为__bases__属性; and the dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute. dict字典是包含类主体定义的命名空间,并成为__dict__属性。

Here's my solution that does take into account base classes of both the parent and the child classes.这是我的解决方案,它考虑了父类和子类的基类。

import inspect    

def inherit_from(Child, Parent):

    # Prepare bases
    child_bases = inspect.getmro(Child)
    parent_bases = inspect.getmro(Parent)
    bases = tuple([item for item in parent_bases if item not in child_bases]) + child_bases

    # Construct the new return type
    Child = type(Child.__name__, bases, Child.__dict__.copy())

    return Child

Another option is not to change the class hierarchy dynamically but to decorate instances of objects with the new functionality.另一种选择不是动态更改类层次结构,而是使用新功能装饰对象的实例。 This is generally cleaner and easier to debug, because you only change objects that your code is in controls without having to make a cross cutting change to the whole class hierarchy.这通常更清晰且更易于调试,因为您只需更改代码在控件中的对象,而无需对整个类层次结构进行横向更改。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM