By generating the control class metaclass

Custom metaclass: controlling the generated class: class name can be controlled, the control may be integrated into the parent class, the class name of the control space

type
Custom metaclass must be integrated type, write a class that inherits this class type called metaclass

class Mymeta(type):
  #def __init__(self,*args,**kwargs):
  def __init__(self,name,bases,dic):
    #sef就是Person类
    print(name)
    print(bases)
    print(dic)
    #加限制 控制类名必须以sb开头
    if not name.startswith('sb')
            raise Exception('类名没有以sb开头')
    #类必须加注释
    print(self.__dict__['__doc__'])
 metaclass = Mymeta 指定这个类生成的时候,用自己写的Mymeta这个元类
class Person(object,metaclass=Mymeta):
  '''
  注释
  '''
  school = 'oldboy'
  def __init__(self,name):
        self.name =name 
  def score(self):
        print('分数是100')
p =Person()

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')

Guess you like

Origin www.cnblogs.com/luodaoqi/p/11528874.html