from time import ctime
import inspect
class MetaC(type):
def __init__(cls,name,bases,attrd):
print isinstance(cls,MetaC)
print inspect.isclass(cls)
super(MetaC,cls).__init__(name,bases,attrd)
print "careated %s" %ctime()
class Foo(object):
__metaclass__=MetaC
def __init__(self):
print "i am here "
我得到了这个输出:
True
True
careated Fri Feb 8 12:33:32 2013
cls
类MetaC
方法中的参数(__init__
),
cls
是class
还是instance
?
答案 0 :(得分:1)
cls
是一个类和一个实例。类只是元类的一个实例。
>>> class MetaC(type):
... def __init__(cls, name, bases, attrs):
... print 'cls: ', cls
... print 'cls is instance of MetaC: ', isinstance(cls, MetaC)
...
>>> class C(object):
... __metaclass__ = MetaC
...
cls: <class '__main__.C'>
cls is instance of MetaC: True