Arun Kaliraja Baskaran
Arun Kaliraja Baskaran

Reputation: 1086

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??

Upvotes: 3

Views: 267

Answers (2)

Maninder Singh
Maninder Singh

Reputation: 849

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.."

Upvotes: 1

jeffknupp
jeffknupp

Reputation: 6274

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

Upvotes: 3

Related Questions