I would like to choose a subclass at instantiation to select specific attributes from certain classes. I've worked out the following:
Code
class Foo:
a = "foo"
def __init__(self, dtype=Bar):
self.__class__ = dtype
class Bar:
b = "bar"
class Baz(Bar):
c = "baz"
Demo
Foo(dtype=Bar).b
# 'bar'
Foo(dtype=Baz).b
# 'bar'
Foo(dtype=Baz).c
# 'baz'
This gives the desired result, selecting specific attributes from Bar
while optionally extending features with Baz
. Unlike subclassing however, we have no access to Foo
's attributes.
Foo(dtype=Baz).a
# AttributeError: 'Baz' object has no attribute 'a'
There are occasions when not all attributes are desired, so subclassing Foo(Baz)
is not preferred.
What's the idiomatic analog to accomplish this in Python?