一般定义方法:
1 class Chinese(object, metaclass=type): 2 country = 'China' 3 4 def __init__(self, name, age): 5 self.name = name 6 self.age = age 7 8 def talk(self): 9 print('%s is talking' % self.name) 10 11 Chinese = type(class_name, class_bases, class_dic)
把metaclass元类换成自己定义的类Mymeta
1 class Chinese(object, metaclass=Mymeta): 2 country = 'China' 3 4 def __init__(self, name, age): 5 self.name = name 6 self.age = age 7 8 def talk(self): 9 print('%s is talking' % self.name) 10 11 Chinese = Mymeta(class_name, class_bases, class_dic)
对Mymeta进行定义:
1 class Mymeta(type): 2 def __init__(cls, class_name, class_bases, class_dic): 3 print(class_name) 4 print(class_bases) 5 print(class_dic) 6 7 super(Mymeta, cls).__init__(class_name, class_bases, class_dic) 8 9 10 class Chinese(object, metaclass=Mymeta): 11 country = 'China' 12 13 def __init__(self, name, age): 14 self.name = name 15 self.age = age 16 17 def talk(self): 18 print('%s is talking' % self.name) 19 20 结果为: 21 22 Chinese 23 (<class 'object'>,) 24 {'__module__': '__main__', '__qualname__': 'Chinese', 'country': 'China', '__init__': <function Chinese.__init__ at 0x000001A891E9B620>, 'talk': <function Chinese.talk at 0x000001A891E9B6A8>}
在Mymeta中可以设置控制条件,对生成的类进行控制,如:
1 if not class_name.istitle(): 2 raise TypeError('类名的首字母必须大写') 3 4 小写就会报错,报错为: 5 6 Traceback (most recent call last): 7 File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/27 自定义元类控制类的行为.py", line 13, in <module> 8 class chinese(object, metaclass=Mymeta): 9 File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/27 自定义元类控制类的行为.py", line 8, in __init__ 10 raise TypeError('类名的首字母必须大写') 11 TypeError: 类名的首字母必须大写
对注释进行控制:
1 if '__doc__' not in class_dic or not class_dic['__doc__'].strip(): 2 raise TypeError('必须有注释,且注释不能为空')
如果没有注释或者注释为空,就会报错,报错为:
1 Traceback (most recent call last): 2 File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/27 自定义元类控制类的行为.py", line 16, in <module> 3 class Chinese(object, metaclass=Mymeta): 4 File "C:/Users/xu516/PycharmProjects/Python全栈开发/第三模块/面向对象编程/27 自定义元类控制类的行为.py", line 11, in __init__ 5 raise TypeError('必须有注释,且注释不能为空') 6 TypeError: 必须有注释,且注释不能为空
加上注释就不会报错了。