问题
Source: Python and the Singleton Pattern
According to most upvoted comment in the top answer init gets called multiple times if new returns class instance.
So I checked this:
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
print 'Singleton.__new__ called with class', cls
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class Cache(Singleton):
def __init__(self, size=100):
print 'I am called with size', size
class S(Singleton):
def __init__(self, param):
print 'I am S with param', param
c = Cache(20)
s = S(10)
Result:
Singleton.__new__ called with class <class '__main__.Cache'>
I am called with size 20
Singleton.__new__ called with class <class '__main__.S'>
I am S with param 10
Apparently init does not called more than once in a class inheriting from Singleton. Has smth changed in Python that handles this in the meantime (considering the question was asked in 2008), or am I missing smth here?
回答1:
Please replace your two last lines with
for x in range(5):
c = Cache(x)
s = S(x)
and post the result.
回答2:
From the print result it is obvious that __init__
is called upon construction of each new Cache
and S
object.
When you create an instance of a class (eg Cache(10)
) Python first creates a new instance of it using __new__
then initializes it using __init__
.
In other words apparently you misread something.
来源:https://stackoverflow.com/questions/18383970/does-init-get-called-multiple-times-with-this-implementation-of-singleton