code show as below:
# -*- coding:gb2312 -*-
class Dog(object):
__instance = None
__init_flag = False
def __new__(cls,name):
if cls.__instance == None:
cls.__instance = object.__new__(cls)
return cls.__instance
else:
return cls.__instance
def __init__(self,name):
#self.name = name
if self.__init_flag == False:
#__init_flag = True
self.name = name
__init_flag = True
a = Dog("旺财")
print(id(a))
print(a.name)
b = Dog("哮天犬")
print(id(b))
print(b.name)
Results of the:
my question:
According to my idea, what I wrote in this code is to design a Dog class and then create a singleton object (the first red box code in), that is, the final instances a and b are actually the same thing.
Then I set up this singleton object and initialized it only once (see the code in the second red box). In other words, after the instance a is created, its name is Wangcai, then the instance b After creation, it should not be initialized, so it should be impossible to print the name Roaring Dog. According to my idea, the result that should be printed is two prosperous wealth. Why is the result now different from what I expected?
In fact, you have already implemented the singleton object. You can see it from the results of
id
. As for why your results are different twice? Because creating a return is one thing, initialization is another. In__new__
, it is confirmed that no new instance will be created, and the old instance will be returned, but this does not affect the next__init__
initialization action, and the__init_flag = True
you modified is only in theinstance object
That’s it, it has not been modified to theclass
side, so your judgment is invalid. Only the__init_flag
that has been modified to theclass
side is valid, so the code is corrected to:Two more suggestions:
When judging whether an object is None, do not use
==
, instead useis
:cls.__instance is None
To determine whether it is equal to
false
, do not use==
, it should benot
:if not self.__init_flag