Using python 3.x, I would like to have a method of a class that returns an instance of the same class; it should be an inheritable method such that sub-classes of the class can call the function to return an instance of the sub-class, not the super-class.
What I would like to see is something like this
class MyClass():
...
def newInstance():##return a new instance of MyClass
class subClass(MyClass):##inherits newInstance from MyClass, but will return an instance of subClass
...
a = MyClass()
b = subClass()
c = a.newInstance()##a new instance of MyClass
d = b.newInstance()##a new instance of subClass
The following isn't inheritable in the right way
class MyClass()
.
.
.
def newInstance(self)##return a new instance...
out = MyClass()
return out##a sub-class would return an instance of the superclass, not it's own class...
I tried this
class MyClass()
.
.
.
def newInstance(self)##return a new instance...
x = self.__class__ ##doesn't work, returns NoneType
out = x()
return out
which gives a TypeError 'NoneType' object is not callable.
I also tried
def newInstance(self)##return a new instance...
out = self.__init__()
return out
which also returns a NoneType object.