自定义元类控制类的创建
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().__init__(class_name, class_bases, class_dic)
class Chinese(object, metaclass=Mymeta):
'''
xxx
'''
country = 'China'
def __init__(self, name, age):
self.name = name
self.age = age
def talk(self):
print('%s is talking' % self.name)
# Chinese = Mymeta(class_name, class_bases, class_dic)
自定义元类控制类的实例化行为
# 知识储备:__call__方法
class Foo:
def __call__(self, *args, **kwargs):
print(self)
print(args)
print(kwargs)
obj = Foo()
obj(1,2,3,a=1,b=2,c=3) # obj.__call__(obj,1,2,3,a=1,b=2,c=3)
# 元类内部也应该有一个__call__方法,会在调用Foo时触发执行
# Foo(1,2,x=1) # Foo.__call__(1,2,x=1)
自定义元类控制类的实例化行为的应用
实现方式一:
# 单例模式
class MySQL:
__instance = None
def __init__(self):
self.host = '127.0.0.1'
self.port = 3306
@classmethod
def singleton(cls):
if not cls.__instance:
obj = cls()
cls.__instance = obj
return cls.__instance
obj1 = MySQL.singleton()
obj2 = MySQL.singleton()
obj3 = MySQL.singleton()
print(obj1)
print(obj2)
print(obj3)
# <__main__.MySQL object at 0x1045a13c8>
# <__main__.MySQL object at 0x1045a13c8>
# <__main__.MySQL object at 0x1045a13c8>
实现方式二:
# 元类的方式
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().__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)
self.__instance = obj
return self.__instance
class Mysql(object,metaclass=Mymeta):
'''
xxxx
'''
def __init__(self):
self.host = '127.0.0.1'
self.port = 3306
obj1 = Mysql()
obj2 = Mysql()
obj3 = Mysql()
print(obj1 is obj2 is obj3)