• 自定义元类控制类的创建


    # Chinese = Mymeta(class_name,class_bases,class_dic)
    # 创建元类如下:


    class Mymeta(type):
    def __init__(self, class_name, class_bases, class_dic):
    # print(class_name)
    # print(class_bases)
    # print(class_dic)
    # 打印结果如下:
    '''
    Chinese
    (<class 'object'>,)
    {'__module__': '__main__', '__qualname__': 'Chinese',
    'country': 'china', '__init__': <function Chinese.__init__ at 0x0000019CC0750AE8>,
    'talk': <function Chinese.talk at 0x0000019CC0750B70>}
    '''

    super(Mymeta, self).__init__(class_name, class_bases, class_dic)


    class Chinese(object, metaclass=Mymeta): # metaclass 元类
    country = 'china'

    def __init__(self, name, age):
    self.name = name
    self.age = age

    def talk(self):
    print('%s is talking' % self.name)


    # ------------例子控制类----------------------------------------


    class Mymeta(type):
    def __init__(self, class_name, class_bases, class_dic):
    if not class_name.istitle(): # class_name 首字母不是大写就报类型错误
    raise TypeError('类型错误')
    if '__doc__' not in class_dic or not class_dic['__doc__'].strip():
    raise TypeError('必需要有注释且不能为空')

    super(Mymeta, self).__init__(class_name, class_bases, class_dic)


    class Chinese(object, metaclass=Mymeta): # metaclass 元类
    """
    这是中国人的类
    """
    country = 'china'

    def __init__(self, name, age):
    self.name = name
    self.age = age

    def talk(self):
    print('%s is talking' % self.name)

  • 相关阅读:
    springAOP实现原理
    cglib用法
    git 用法
    java基础算法之快速排序
    记一次与a标签相遇的小事
    java设计模式之建造者模式
    HashMap源码分析
    Linux下安装nginx
    java设计模式之策略模式
    java设计模式之中介者模式
  • 原文地址:https://www.cnblogs.com/kingforn/p/11356145.html
Copyright © 2020-2023  润新知