Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there generic inheritance in python?

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?

like image 431
Karan Avatar asked Nov 18 '25 14:11

Karan


1 Answers

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.

like image 193
Thomas Wouters Avatar answered Nov 20 '25 02:11

Thomas Wouters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!