MetaClass
from types import MethodType
class A:
pass
def say(self):
print("this is say()")
a = A()
a.say = MethodType(say, A)
a.say()
>>>
this is say()
type
# 1. 定义类应该具有的成员函数
def say(self):
print("this is say()")
def eat(self):
print("this is eat()")
# 2. 用 type 来创建一个类
A = type("AName", (object,), {"class_say": say, "class_eat": eat})
# 3. 像正常访问一样使用类
a = A()
a.class_say()
a.class_eat()
>>>
this is say()
this is eat()
MetaClass
# 元类写法是固定的,必须继承自 type
# 元类一般命名以 MetaClass 结尾
class ExampleMetaClass(type):
def __new__(cls, region, gender, attrs):
print("this is MetaClass")
attrs['id_num'] = '9527'
attrs['age'] = "18"
return type.__new__(cls, region, gender, attrs)
# 元类定义完就可以使用
class Person(object, metaclass=ExampleMetaClass):
pass
york = Person()
print(york.id_num)
>>>
this is MetaClass
9527