2
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  

类 方法 中的argument( cls) ,MetaC__init__

cls 一个class还是一个instance

4

1 回答 1

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
于 2013-02-08T04:44:16.050 回答