如果使用Python进行鸭式打字,您是否应该测试isinstance? [英] If duck-typing in Python, should you test isinstance?
问题描述
您有一个需要相等测试的Python类. Python应该使用鸭式输入法,但是在 eq 函数中包含或排除isinstance测试(更好/更准确)是吗?例如:
You have a Python class which needs an equals test. Python should use duck-typing but is it (better/more accurate) to include or exclude an isinstance test in the eq function? For example:
class Trout(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
return isinstance(other, Trout) and self.value == other.value
推荐答案
在__eq__
方法中使用isinstance很常见.这样做的原因是,如果__eq__
方法失败,则它可能会从另一个对象回退到__eq__
方法.大多数常规方法都被显式调用,但__eq__
被隐式调用,因此它需要更频繁地跳转.
Using isinstance in __eq__
methods is pretty common. The reason for this is that if the __eq__
method fails, it can fallback on an __eq__
method from another object. Most normal methods are called explicitly, but __eq__
is called implicitly, so it requires look-before-you-leap more frequently.
编辑(感谢提醒,斯文·马纳赫):
EDIT (thanks for the reminder, Sven Marnach):
要使其回退,可以返回NotImplemented单例,如本例所示:
To make it fallback, you can return the NotImplemented singleton, as in this example:
class Trout(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, Trout):
return self.value == other.value
else:
return NotImplemented
假设RainbowTrout
知道如何将自己与Trout
或另一个RainbowTrout
进行比较,但是Trout
仅知道如何将自身与Trout
进行比较.在此示例中,如果测试mytrout == myrainbowtrout
,Python将首先调用mytrout.__eq__(myrainbowtrout)
,注意它失败,然后调用myrainbowtrout.__eq__(mytrout)
,这将成功.
Suppose a RainbowTrout
knows how to compare itself to a Trout
or to another RainbowTrout
, but a Trout
only knows how to compare itself to a Trout
. In this example, if you test mytrout == myrainbowtrout
, Python will first call mytrout.__eq__(myrainbowtrout)
, notice that it fails, and then call myrainbowtrout.__eq__(mytrout)
, which succeeds.
这篇关于如果使用Python进行鸭式打字,您是否应该测试isinstance?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!