gpt4 book ai didi

python - , 的区别?

转载 作者:太空宇宙 更新时间:2023-11-03 14:58:50 24 4
gpt4 key购买 nike

根据 here :

The __mro__ attribute of the type lists the method resolution search order used by both getattr() and super(). The attribute is dynamic and can change whenever the inheritance hierarchy is updated.

我用这个尝试了 __mro__ 属性:

class a:
def __init__(self):
self.testValue = 123

然后我输入:

type(a).__mro__
(<type 'classobj'>, <type 'object'>)

classobj 是什么?它与 object 有什么区别?

加1

可能我今天有点晕...不过我猜classobj就是class a的意思吧?所以上面的输出只是说方法解析顺序是首先 class a 然后是 type object

最佳答案

首先请注意,在 Python 2.x 中,语法:

class XXX:
# whatever

将产生一个“旧式”类。您可以在 the fine manual 中阅读更多关于“旧式”与“新式”类的信息, 关于 this doc pagePython wiki

然后,在你的情况下,你不是在请求类 a 的 mro,而是在请求类 a 类型的 mro(这就是 type(a) 返回),在本例中为 classobj 类型。但是您不必担心旧式类、classobj 等,除非您必须维护或处理遗留代码。郑重声明,大多数 Python 的标准 OO 特性(包括 super()、描述符等)在旧式类上无法正常工作,所以不要使用它们,也不要尝试了解与使用旧式类的"new"(好吧,到现在大约 10 岁)对象模型有关的东西...

TL;DR:你想要:

class A(object):
# this is a new-style class

Maybe I am a bit dizzy today... But I guess the classobj just means class a, right?

错了。 classobj 是一种特殊类型,用作旧式类的元类。元类是类的类(因为类是对象,所以它们是类的实例)。

So the above output just says the method resolution order is first class a then type object.

不,它说 classobj 类型的 mro 首先是 classobj 然后是 object

如果您想要 a 类的 mro,那么只需提出要求 - 然后您就会发现为什么您不应该在旧式类上评估新式特性:

>>> class a: pass
...
>>> a.__mro__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class a has no attribute '__mro__'

现在与新式类进行比较:

>>> class Foo(object): pass
...
>>> Foo.__mro__
(<class '__main__.Foo'>, <type 'object'>)
>>>

关于python - <type 'classobj'>, <type 'object'> 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40171871/

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