通过元类来控制类的产生

通过元类来控制类的产生

自定义元素:来控制类的产生,可以控制类名,可以控制类的继承父类,控制类的名称空间

自定义元类必须继承type,写一个类继承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开头')
        #练习二:类必须加注释
        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')

猜你喜欢

转载自www.cnblogs.com/aden668/p/11453555.html