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)
然而,当我们编写元类时,它应该从type继承,我无法理解背后的原因:
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继承,当我们明确调用new、init、call函数时。同时,“描述符'init'需要一个'type'对象但收到了一个'instance'”这个错误只有在创建i=instance (ob)时才会发生。