元类中的类或实例?

时间:2013-02-08 04:39:58

标签: python instance metaclass

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  

clsMetaC方法中的参数(__init__),

clsclass还是instance

1 个答案:

答案 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