- 参考资料
https://www.liaoxuefeng.com/wiki/1016959663602400/1017592449371072
https://stackoverflow.com/questions/18513821/python-metaclass-understanding-the-with-metaclass
- return type(name, bases, attr) 和 return type.new(cls, 'name',(object,), {})
# # type 类创建对象方法1【class_ = ModelObject('name',(Test,),{})】
class SetterAwareType(type): # 元类
def __new__(cls, *args):
print('in SetterAwareType __new__')
return type.__new__(cls, *args) # return 方式1,这种方式执行__init__函数
name, bases, attr = args[:3]
return type(name, bases, attr) # return 方式2 ,这种方式不走__init__函数了,不打印 in SetterAwareType __init__
def __init__(cls, *args):
print('in SetterAwareType __init__')
return type.__init__(cls, *args) # TypeError: type.__init__() takes 1 or 3 arguments
class ModelObject(SetterAwareType):
pass
class Test(object):
def test(self):
print('in class Test test')
class_ = ModelObject('name',(Test,),{})
obj = class_()
obj.test()
# type 类创建对象方法2【a = ModelObject()】
class SetterAwareType(type): # 元类
def __new__(cls, *args):
print('in SetterAwareType __new__')
return type.__new__(cls, 'name',(object,), {}) # 'name' 直接传入了
def __init__(cls, *args):
print('in SetterAwareType __init__')
return super(SetterAwareType, cls).__init__(cls, *args)
# return type.__init__(cls, *args) # TypeError: type.__init__() takes 1 or 3 arguments
class ModelObject(SetterAwareType):
def test(self):
print('in ModelObject copy')
a = ModelObject()
a.test()