gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:17:18 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com