I encountered a strange bug in python where using the __new__
method of a class as a factory would lead to the __init__
method of the instantiated class to be called twice.
The idea was originally to use the __new__
method of the mother class to return a specific instance of one of her children depending on the parameters that are passed, without having to declare a factory function outside of the class.
I know that using a factory function would be the best design-pattern to use here, but changing the design pattern at this point of the project would be costly. My question hence is: is there a way to avoid the double call to __init__
and get only a single call to __init__
in such a schema ?
class Shape(object):
def __new__(cls, desc):
if cls is Shape:
if desc == 'big': return Rectangle(desc)
if desc == 'small': return Triangle(desc)
else:
return super(Shape, cls).__new__(cls, desc)
def __init__(self, desc):
print "init called"
self.desc = desc
class Triangle(Shape):
@property
def number_of_edges(self): return 3
class Rectangle(Shape):
@property
def number_of_edges(self): return 4
instance = Shape('small')
print instance.number_of_edges
>>> init called
>>> init called
>>> 3
Any help greatly appreciated.
return Rectangle.__new__(Rectangle)
because this would guarantee that__new__
ofRectangle
gets called if it's defined? – Greenebaum