一. 元类(metaclass)
在python中一切皆对象,那么我们用class关键字定义的类本身也是一个对象,负责产生该对象的类称之为元类,即元类可以简称为类的类
https://www.cnblogs.com/nickchen121/p/10992975.html 详细.........
https://www.cnblogs.com/linhaifeng/articles/8029564.html 详细.......
class Foo(object):
...
aa=Foo()
print(type(aa)) # <class '__main__.Foo'>
print(type(Foo)) # <class 'type'>
print("***********************************************************")
Per=type('Per',(object,),{"x":1})
print(Per.__dict__)
print(Per.x)
print("***********************************************************")
# type 实例化 就是类的类 type 元类
def __init__(self,name,age):
self.name=name
self.age=age
def aa(self):
print("这是类的类 元类type创建的哈哈哈哈哈哈")
print(self.name)
Per=type('Per',(object,),{'x':1,' __init__':__init__,'aa':aa})
print(Per)
print(Per.__dict__)
# a1=Per("张三",55)
print(Per.x)
#
# f1=Per("展示柜",55)
# print(f1.name)
创建类的3个要素:类名,基类,类的名称空间
People = type(类名,基类,类的名称空间)
class_name = 'People' # 类名
class_bases = (object, ) # 基类
# 类的名称空间
class_dic = {}
class_body = """
country='China'
def __init__(self,name,age):
self.name=name
self.age=age
def eat(self):
print('%s is eating' %self.name)
"""
exec(
class_body,
{},
class_dic,
)