Python constructor for native instance

class Foo(): def __init__(self): pass def create_another(self): return Foo() # is not working as intended, because it will make y below becomes Foo class Bar(Foo): pass x = Bar() y = x.create_another() 

y must be of class Bar not Foo.

Is there something like: self.constructor() instead?

+7
source share
1 answer

For new-style classes, use type(self) to get the "current" class:

 def create_another(self): return type(self)() 

You can also use self.__class__ , as this value will use the type() value, but it is recommended that you always use the API method.

For old-style classes (python 2, not inheriting from object ), type() not so useful, so you are forced to use self.__class__ :

 def create_another(self): return self.__class__() 
+24
source

All Articles