Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling super class init when child class is created using type()

I am trying to create a class dynamically using the python type() method.

So, say i have a base class 'A'

>>> class A:
    def __init__(self):
        print("I am in init of A..")

Now i create a child class 'C' by using type method

>>> C = type('C',(A,),{})

When i create an object

>>> c = C()
I am in init of A..

The init of base class is also called correctly..

now i want to do something in my init method and i write a custom init method..

>>> def BsInit(self):
    print ("I am in init of B..")

and i create a class 'B' and create an instance..

>>> B = type('B',(A,),{'__init__':BsInit})
>>> b = B()
I am in init of B..

The init of class A is not called at all..

So tried to modify BsInit method like this:

>>> def BsInit(self):
    super().__init__();
    print ("I am in init of B..")

And i get the below error when i create an instance...

>>> B = type('B',(A,),{'__init__':BsInit})
>>> b = B()
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    b = B()
  File "<pyshell#19>", line 2, in BsInit
    super().__init__();print ("I am in init of B..")
RuntimeError: super(): __class__ cell not found

All the examples i find with custom init using type() are really simple, like just initialising a variable.. but if i want to call base class Init too how to do it??

like image 682
Arun Kaliraja Baskaran Avatar asked Feb 16 '26 21:02

Arun Kaliraja Baskaran


2 Answers

You need to call it like so: super(B, self).__init__().

like image 143
jeffknupp Avatar answered Feb 19 '26 09:02

jeffknupp


You need to pass cls in init method instead of self. Below is the solution of your problem:

def init(cls):
    super(type(cls), cls).__init__()

B = type('B',(A,),{'__init__':init})
b = B()
"I am in init of A.."
like image 39
Maninder Singh Avatar answered Feb 19 '26 09:02

Maninder Singh



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!