python - 元类中是类还是实例?

标签 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  

MetaC__init__方法中的参数(cls),

cls还是实例

最佳答案

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

关于python - 元类中是类还是实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14765780/

相关文章:

python - 为多态身份增强 SQLAlchemy 语法

python - Django ConnectionAbortedError : [WinError 10053] An established connection was aborted by the software in your host machine

Java:确定静态方法是从实例调用还是静态调用

java - 如何保存字符串?

python - 为什么 python 字典在我启动一个新的类实例时会记住前一个实例的值?

python - 查找在 Python 中重新定义之前使用的 __metaclass__

python - SQLAlchemy 中的动态类创建

javascript - 在 ES2016 或更高版本中,像这样的列表推导式相当于什么?

python - 在 Python 中生成漂亮的 diff html

python - 我应该写一个 setter 来访问类变量进行测试吗?