Reputation: 23
I have a class foo that inherits from bar. However I also want to have the option when initializing foo to have it inherit from wall instead of bar. I am thinking something like this:
class Foo():
def __init__(self, pclass):
self.inherit(pclass)
super().__init__()
Foo(Bar) # child of Bar
Foo(Wall) # child of Wall
Is this possible in Python?
Upvotes: 0
Views: 77
Reputation: 362717
It's not really possible easily, because classes are defined at the time of executing the class block, not at the time of creating an instance.
A popular design pattern to use instead would be to put the common code into a mixin:
class FooMixin:
# stuff needed by both Foo(Bar) and Foo(Wall)
class FooBar(FooMixin, Bar):
...
class FooWall(FooMixin, Wall):
...
Then you can use some sort of factory function:
def make_foo(parent, *init_args, **init_kwargs):
if parent is Bar:
Foo = FooBar
elif parent is Wall:
Foo = FooWall
return Foo(*init_args, **init_kwargs)
Upvotes: 3