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

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?

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

reply all(1)
阿神

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 the instance object That’s it, it has not been modified to the class side, so your judgment is invalid. Only the __init_flag that has been modified to the class side is valid, so the code is corrected to:

class Dog(object):
    ....(其他内容请自行补充)...
    def __init__(self, name):
            # self.name = name
            if not self.__init_flag:
                # __init_flag = True
                self.name = name
                Dog.__init_flag = True   # 修改基类的__init_flag 

Two more suggestions:

  1. When judging whether an object is None, do not use ==, instead use is: cls.__instance is None

  2. To determine whether it is equal to false, do not use ==, it should be not: if not self.__init_flag

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!