table of Contents
Chapter XIII produce, control of the class metaclass
A custom metaclass
Description : A class inherits this class type called metaclass
The purpose : to control the production of class, you can control the class name, parent class can inherit control of the control class name space
Second, write a custom metaclass
The class name of the control class
class Mymeta(type): # def __init__(self,*args,**kwargs): def __init__(self,name,bases,dic): # self 就是Person类 print(name) print(bases) print(dic) # 练习一:加限制 控制类名必须以sb开头 if not name.startswith('sb'): raise Exception('类名没有以sb开头')
The class must annotate
class Mymeta(type): def __init__(self,name,bases,dic): print(self.__dict__['__doc__']) doc=self.__dict__['__doc__'] if not doc: #没有加注释 raise Exception('你的类没有加注释') class Person(object,metaclass=Mymeta): ''' 我加了注释 ''' school='oldboy' def __init__(self,name): self.name=name def score(self): print('分数是100')