问题
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