class Dog(type):
def __init__(self, class_name, class_bases, class_dic):
super().__init__(class_name, class_bases, class_dic)
self.__instance = None # 定义一个为空对象
def __call__(self, *args, **kwargs): # 调用__call__方法
if not self.__instance:
instance = object.__new__(self)
self.__init__(instance, *args, **kwargs)
self.__instance = instance
return self.__instance
# 单例 创建的对象中 有且仅有一个实例
class TuGou(metaclass=Dog):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self): #调用__str__打印对象
return '我叫{},今年{}岁'.format(self.name, self.age)
obj1 = TuGou('大花', 2)
obj2 = TuGou('小花', 3)
obj3 = TuGou('二花', 4)
print(obj1)
print(obj2)
print(obj3)
print(obj1 is obj2 is obj3) # 判断obj1,obj2,obj3三个是否为同一实例
print(obj1 == obj2 == obj3)
元类的单例
最新推荐文章于 2023-06-24 20:24:44 发布