[Python Newbie] Ask a question about initializing an object once
我想大声告诉你
我想大声告诉你 2017-06-28 09:24:24
0
1
547

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?

我想大声告诉你
我想大声告诉你

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!