从子级返回父类实例的Python方法

时间:2020-04-13 07:44:44

标签: python-3.x oop multiple-inheritance mixins

在多重继承下,孩子总是从Mixin和某种类型的Thing继承,我如何在Mixin中获得一个方法以使孩子能够返回父对象的实例Thing?下面的代码通过直接调用“方法解析顺序”图而起作用,但是似乎不合逻辑。有更好的方法吗?

class Thing1(object):
    def __init__(self, x=None):
        self.x = x

class Thing2(object):
    def __init__(self, x=None):
        self.x = 2*x

...


class Mixin(object):
    def __init__(self, numbers=(1,2,3)):
        self.numbers = numbers
        super().__init__()

    def children(self):
        test_list = []

        for num in self.numbers:
            # What is a better way to do this?
            test_list.append(self.__class__.__bases__[1](x=num))

        return test_list

class CompositeThing1(Mixin, Thing1):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def test(self):
        for child in self.children():
            print(child.x)

obj = CompositeThing1()
obj.test()

0 个答案:

没有答案