gpt4 book ai didi

python - 可以同时扩展旧样式类和新样式类吗?

转载 作者:太空狗 更新时间:2023-10-30 01:10:37 25 4
gpt4 key购买 nike

当我扩展一些工具生成的类时,直到我尝试使用 super() 才意识到它们是旧式类。 super() 不适用于旧样式类,所以我得到了这个错误:

TypeError: super() argument 1 must be type, not classobj

例如,试试这个片段:

>>> class A:
... def greet(self):
... print "A says hi"
...
>>> class B(A):
... def greet(self):
... print "B says hi"
...
>>> super(B, B()).greet()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: super() argument 1 must be type, not classobj

我很好奇如果我从 object 扩展 B 并使其成为一个新的样式类会发生什么,它似乎使 super() 工作。

>>> class B(A, object):
... def greet(self):
... print "B says hi"
...
>>> super(B, B()).greet()
A says hi

这是一个合适的解决方法,还是我以后会产生一些不良后果?

最佳答案

自从在 Python 2.2 中引入新式类以来,它们一直被推荐在 Python 中实践。在 Python 3.x 中,只有新式类可用。因此,我建议您将类(class)切换为新式。

我不知道您可能因此而遇到任何实际问题。在大多数情况下,新式类只是带来新功能,例如 super() 实际工作。如果您的代码以巧妙的方式依赖于旧式类的语义,那么该代码当然会中断。 (想到的唯一例子是著名的 Alex Martelli 的著名 Borg pattern。)

Here是 Python 引用手册的链接,用于讨论新式类与旧式(“经典”)类的对比。和 here是经典文章的链接,其中 Guido van Rossum 解释了为什么引入新式类。

我在我的代码中只使用新式类,我鼓励你也这样做。

关于python - 可以同时扩展旧样式类和新样式类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1641958/

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