Say I built some classes containing some instance methods:
class A:
def func_of_A(self):
print("foo")
class B:
def func_of_B(self):
print("bar")
How can I construct an object/variable c
that is an instance of both A
and B
, so that I can call both c.func_of_A()
and c.func_of_B()
?
I could of course build a new class inheriting from A
and B
and make c
a member of that:
class C(A,B):
pass
c = C()
But that is not what I am looking for. I would rather not create a new class every time I am planning to use a combination of already built ones.
I could also create a function to dynamically define a new class and return an instance of it:
def merge(*inherit_from):
class D(*inherit_from):
pass
return D()
c = merge(A,B)
but this is beyond cursed, because now merge(A,B)
, merge(A)
and merge(B)
all return the same type <class '__main__.merge.<locals>.D'>
.
There should be an intended way to do this, shouldn't?
Is there a solution that scales well with the number of classes involved? If I already have class A1
, class A2
, ..., class A100
and I want to construct some c
to be an instance of class A2, class A23, class A72, class A99
but not the others how would I do that? Creating a new class for every combination is pretty much impossible, given the ~2^100 combinations.
CodePudding user response:
You can use type()
for that as @deceze mentioned
>>> class A:
... def a():
... pass
...
>>> class B:
... def b():
... pass
...
>>> def merge(name: str, *parents):
... return type(name, parents, dict())
...
>>> C = merge("C", A, B)
>>> C.a()
>>> C.b()
>>>