自定义元类控制类的创建

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

posted on 2019-08-15 09:52  kingforn  阅读(750)  评论(0编辑  收藏  举报