3

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

2 Answers2

3

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

jeffknupp
  • 5,966
  • 3
  • 28
  • 29
1

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.."
Maninder Singh
  • 829
  • 1
  • 7
  • 13
  • I think cls ans self are both same in this context.. the difference between cls and self is just a coding convention: https://stackoverflow.com/questions/4613000/what-is-the-cls-variable-used-in-python-classes so the below one too works: def BsInit(self): super(type(self),self).__init__(); print ("I am in init of B..") – Arun Kaliraja Baskaran Jun 09 '17 at 06:32