在“Think Python:如何像计算机科学家一样思考”中,作者指出:
For built-in types, there are relational operators (
<
,>
,==
, etc.) that compare values and determine when one is greater than, less than, or equal to another. For programmer-defined types, we can override the behavior of the built-in operators by providing a method named__lt__
, which stands for "less than".
这是 __lt__
的代码为 Card
实现的方法:
# inside class Card:
def __lt__(self, other):
t1 = self.suit, self.rank
t2 = other.suit, other.rank
return t1 < t2
但是__lt__
未定义 Card
之前,那么我们如何覆盖它的行为呢?我们在这里为 __lt__
定义一个新行为使其与 Card
一起工作对象。所以,__lt__
仍然适用于数字、字符串等(据我所知,所有这些)。
我说作者(我非常欣赏他的作品)不应该使用“override”,这句话对吗?
最佳答案
简短回答:不,您“覆盖”__lt__
的object
.
如果你看一下 object()
上定义的函数:
>>> dir(object())
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', <b>'__lt__'</b>, '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
(列表中有一个'__lt__'
)。
这意味着在 object
的定义中__lt__
定义为:
class object:
# ...
def __lt__(self,value):
"""Return self<value."""
# base implementation: objects are not comparable in Python 3
return NotImplemented
现在如果你写一个类 Card
,你总是继承自 object
(即使您没有提及)。因此,如果您定义自己的 __lt__
,您覆盖 object.__lt__
定义。
换句话说,如果你写:
class Card:
# ...
def __lt__(self, other):
t1 = self.suit, self.rank
t2 = other.suit, other.rank
return t1 < t2
Card
的方法解析顺序 (MRO)将是:
>>> Card.__mro__
(<class '__main__.Card'>, <class 'object'>)
这意味着如果您调用x.__lt__
在Card
上对象x
,它会首先寻找__lt__
在Card
,但如果找不到,它将回退 object
并寻找 __lt__
在那边。所以你的__lt__
“隐藏”原文__lt__
.
正如您可以阅读的那样 here 。 __lt__
, __le__
, __eq__
, __ne__
, __gt__
和__ge__
丰富的比较方法:
These are the so-called "rich comparison" methods. The correspondence between operator symbols and method names is as follows:
x<y
callsx.__lt__(y)
,x<=y
callsx.__le__(y)
,x==y
callsx.__eq__(y)
,x!=y
callsx.__ne__(y)
,x>y
callsx.__gt__(y)
, andx>=y
callsx.__ge__(y)
.A rich comparison method may return the singleton
NotImplemented
if it does not implement the operation for a given pair of arguments. By convention,False
andTrue
are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will callbool()
on the value to determine if the result is true or false.
关于python - 在 Python 中,说我们 "override"内置运算符的行为准确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42863355/