Python 内置的 super() 不违反 DRY 吗? [英] Doesn't Python's super() built-in violate DRY?
问题描述
这显然是有原因的,但我没有足够的经验来识别它.
There is obviously a reason for this but I am not experienced enough to recognise it.
这是 Python docs 中给出的示例:>
This is the example given in the Python docs:
class C(B):
def method(self, arg):
super(C, self).method(arg) # Why do we have to mention 'C' again?
是否有一种不依赖于复制类C"名称的方式从实例方法中知道"类型?看起来这个例子可能会导致类名更新但超级函数调用中的类型参数变得陈旧的情况?
Is there not a way of 'knowing' the type from within the instance method that doesn't rely on duplicating the name of the class 'C'? Seems like the example could lead to a situation where the class name is updated but the type parameter in the super function call becomes stale?
推荐答案
一方面,DRY 更多的是重复大量代码;另一方面,是的,super()
调用中的类名可能会变得陈旧(这发生在我身上).
On the one hand, DRY is more about large sections of code being duplicated; on the other hand, yes, the class name in super()
calls can become stale (it's happened to me).
在 Python 3 中,super()
已经修改为不需要类名,只要函数是在类中定义的——所以不是问题,除非你是猴子补丁.
In Python 3, super()
has been revamped to not require the class name, so long as the function is defined inside the class -- so not a problem unless you are monkey-patching.
这篇关于Python 内置的 super() 不违反 DRY 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!