第十三章、元类之控制类的产生

第十三章、元类之控制类的产生

一、自定义元类

说明:一个类继承type 这种类都叫元类

目的:来控制类的产生,可以控制类名,可以控制类的继承父类,控制类的名称空间

二、写一个自定义元类

  • 控制类的类名

    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开头')
  • 类必须加注释

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

猜你喜欢

转载自www.cnblogs.com/demiao/p/11456270.html