我们可以将函数用作元类,我的理解是它们不是从类型派生的,如下所示:
def test_meta(name, bases, atts):
print("testmeta called for " + name)
return type(name,bases,atts);
class Computer:
__metaclass__ = test_meta
def __init__(self,brand,model,price):
self.brand = brand
self.model = model
self.price = price
#
#
ob = Computer('p1','core2duo',21985.25)
但是,当我们编写元类时,它应该从类型继承,我不明白其背后的原因:
class MyMeta:
def __new__(meta, name, bases, dct):
print ('-----------------------------------')
print ("Allocating memory for class", name)
print (meta)
print (bases)
print (dct)
return type.__new__(meta, name, bases, dct)
def __init__(cls, name, bases, dct):
print ('-----------------------------------')
print ("Initializing class", name)
print (cls)
print (bases)
print (dct)
type.__init__(cls,name, bases, dct)
def __call__(mcs, *args, **kwargs):
print ('-----------------------------------')
print ("calling class")
print mcs
class Computer:
__metaclass__ = MyMeta
def __init__(self,brand,model,price):
self.brand = brand
self.model = model
self.price = price
#
#
ob = Computer('p1','core2duo',21985.25)
例如,在上面的代码中,当我们显式调用类型函数(即<)时,为什么我不理解为什么 MyMeta 类应该从 type 继承 strong>新建,初始化,致电。 同样,仅当创建i = instance(ob)时,才会出现错误“描述符' init '需要一个'type'对象,但收到了一个'instance'”。