Is there generic inheritance in python?
-
26-10-2019 - |
Question
I was wondering if there is generic inheritance in python.
For example,
Class A(object):
def foo():
Class B(object):
def foo():
Class C(<someParentClass>):
def bar():
so effectively, I would like to do something like
myClass1 = C()<A>
myClass2 = C()<B>
Im guessing this is not possible in python, but is there any other way to have a similar effect?
Solution
There's nothing preventing it. Everything in Python is essentially generic. Everything is runtime, including class statements, so you can do something like:
def make_C(parent):
class C(parent):
def bar(self):
...
return C
myClass1 = make_C(A)
myClass2 = make_C(B)
If you want the C class to be a little more descriptive in name or documentation, you can assign the __name__
and __doc__
attributes, or use the three-argument form of type()
instead of the class
statement to create it.
OTHER TIPS
You could derive C
from object
and use
class MyClass1(A, C):
pass
class MyClass2(B, C):
pass
There are many ways achieving the exact effect you described, but I think defining C
as a mix-in class is the most idiomatic approach.