I want to create a class that inherits from two classes (a
and b
) and their sub-classes. The combined child class will not have unique properties or method but will instead inherit everything from their children.
My problem is that I'll need to create an empty class for each possibility of child classes. If class a
has m
sub-classes and class b
has n
sub-classes I'll need to create m*n
empty sub-classes. In reality there m and n are less than 4 but it doesn't seem very pythonic to create lots of empty classes.
Is there a better way of doing this?
I've created a dummy example to hopefully make the problem clear
class BakedItem:
pass
class Fruit:
pass
class Pie(BakedItem):
def bake(self):
pass
def add_pastry(self):
pass
class Tart(BakedItem):
def bake(self):
pass
class Cake(BakedItem):
def bake(self):
pass
class Apple(Fruit):
def flavour(self):
return "apple"
class Blueberry(Fruit):
def flavour(self):
return "Blueberry"
class Blueberry(Fruit):
def flavour(self):
return "Blueberry"
class ApplePie(Apple,Pie):
pass
class AppleCake(Apple,Cake):
pass
class BlueberryTart(Blueberry,Tart):
pass
# Etc (lots of empty multiple inheritance classes)
It sounds like you want a class factory:
def make_baked_type(fruit, bake):
class baked_item(fruit, bake):
pass
return baked_item
ApplePie = make_baked_type(Apple, Pie)
item = ApplePie()
print(item.flavour())
# or
def make_baked_item(fruit, bake):
return make_baked_type(fruit, bake)()
item = make_baked_item(Apple, Pie)
print(item.flavour())