最近在学习元类。
#python3
# coding=utf-8
class ModelMetaclass(type):
def __new__(cls, name, bases, attrs):
print("ainia")
return type.__new__(cls, name, bases, attrs)
class BBB:
def __new__(cls, name, bases, attrs):
print("BBBBB")
return object.__new__(cls, name, bases, attrs)
class Model(metaclass=BBB):
pass
class Model2(metaclass=ModelMetaclass):
pass
#python2
# coding=utf-8
class ModelMetaclass(type):
def __new__(cls, name, bases, attrs):
print("ainia")
return type.__new__(cls, name, bases, attrs)
class BBB(object):
def __new__(cls, name, bases, attrs):
print("BBBBB")
return object.__new__(cls, name, bases, attrs)
class Model(object):
__metaclass__ = BBB
pass
class Model2(object):
__metaclass__ = ModelMetaclass
pass
以上代码另存为test.py,中运行时提示:
Traceback (most recent call last):
File "test2.py", line 18, in
class Model(metaclass=BBB):
File "test2.py", line 15, in __new__
return object.__new__(cls, name, bases, attrs)
TypeError: object() takes no parameters
但是如果我把return object.__new__(cls, name, bases, attrs)修改为return object.__new__(cls)却可以正常输出。
还请各位指教?