Python 中的动态继承 [英] Dynamic inheritance in Python

查看:29
本文介绍了Python 中的动态继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个不同的类实现

Say I have 2 different implementations of a class

class ParentA:
    def initialize(self):
        pass

    def some_event(self):
        pass

    def order(self, value):
        # handle order in some way for Parent A


class ParentB:
    def initialize(self):
        pass

    def some_event(self):
        pass

    def order(self, value):
        # handle order in another for Parent B

我怎样才能基于这样的事情动态地让某些第三类从 ParentAParentB 继承?

How can I dynamically let some 3rd class inherit from either ParentA or ParentB based on something like this?

class MyCode:
    def initialize(self):
        self.initial_value = 1

    def some_event(self):
        # handle event
        order(self.initial_value)


# let MyCode inherit from ParentA and run
run(my_code, ParentA)

推荐答案

简单地将类对象存储在一个变量中(在下面的例子中,它被命名为base),并在class 语句的基类规范.

Simply store the class-object in a variable (in the example below, it is named base), and use the variable in the base-class-spec of your class statement.

def get_my_code(base):

    class MyCode(base):
        def initialize(self):
          ...

    return MyCode

my_code = get_my_code(ParentA)

这篇关于Python 中的动态继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆