一:元类
# 元类,即函数type(clsName,bases,dict)
# 方式一:
# code = """
# country = 'China' #局部名字
# def __init__(self,name,age):
# self.name = name
# self.age = age
# """
# class_dict = {}
# exec(code,{},class_dict) #将字符串中的代码产生的全局名字与值放入第二个参数里,局部名字与值放入第三个参数里
# Chinese = type('Chinese',(object,),class_dict)
# 方式二:
def __init__(self,name,age):
self.name = name
self.age = age
Chinese = type('Chinese',(),{'__init__':__init__,'country':'China'})
c1 = Chinese('rock',18)
print(c1.name,c1.age,c1.country)
# 定制元类,即定制函数type(clsName,bases,dict)
class MyMeta(type): # 继承自元类type,重写__new__方法,从而控制类的属性的创建
def __new__(cls, cls_name,bases,dict):
attrs = ((key,value) for key,value in dict.it