# 单例模式:对一个类多次实例化,但只实例化出同一个对象class Mymeta(type): def __init__(self,class_name,class_bases,class_dic): if not class_name.istitle(): raise TypeError(‘类名的首字母必须大写!‘) if ‘__doc__‘ not in class_dic or not class_dic[‘__doc__‘].strip(): raise TypeError(‘必须有注释,且注释不能为空!‘) super(Mymeta,self).__init__(class_name,class_bases,class_dic) self.__instance = None def __call__(self, *args, **kwargs): if not self.__instance: obj = object.__new__(self) self.__init__(obj,*args, **kwargs) self.__instance=obj return self.__instance class Mysql(object,metaclass=Mymeta): ‘‘‘ MYSQL ‘‘‘ def __init__(self): self.host=‘127.0.0.1‘ self.port=3306 obj1 = Mysql()obj2 = Mysql()obj3 = Mysql() print(obj1)print(obj2)print(obj3)
原文地址:https://www.cnblogs.com/jt925/p/10503480.html
时间: 2024-09-30 10:06:15