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):
        if Dog.__init_flag == False:
            self.name = name
            Dog.__init_flag = True

a = Dog("旺财")
print(id(a))
print(a.name)

b = Dog("哮天犬")
print(id(b))
print(b.name)

打印结果:

2193174953824
旺财
2193174953824
旺财
 
最后附上图便于理解 __new__方法的含义
posted on 2017-08-27 12:32  睡着的糖葫芦  阅读(2441)  评论(0编辑  收藏  举报