zoukankan      html  css  js  c++  java
  • 通过元类来控制类的产生

    通过元类来控制类的产生

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

    自定义元类必须继承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')
    
    
  • 相关阅读:
    【NLP CS224N笔记】汇总
    【NLP CS224N笔记】Lecture 2
    论文摘记 2017.5
    FAST UA API
    FAST Hello World
    NetMagic Simple Overview
    论文摘记 2017.4.25-4.30
    LLDP协议、STP协议 笔记
    FAST:通过Floodlight控制器下发流表
    FAST:NetMagic交换机 与 Floodlight控制器 连接实战
  • 原文地址:https://www.cnblogs.com/aden668/p/11453555.html
Copyright © 2011-2022 走看看