Pythonic way of returning instances of parent class from child

懵懂的女人 提交于 2020-04-18 05:47:39

问题


Under multiple inheritance, where the child always inherits from Mixin and some type of Thing, how do I get a method in Mixin to enable the child to return instances of the parent Thing? The following code works by directly calling into the Method Resolution Order graph, but seems unpythonic. Is there a better way?

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()

来源:https://stackoverflow.com/questions/61183492/pythonic-way-of-returning-instances-of-parent-class-from-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!