python - 在 Python 中,说我们 "override"内置运算符的行为准确吗?

标签 python oop operator-overloading operators

在“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 calls x.__lt__(y), x<=y calls x.__le__(y), x==y calls x.__eq__(y), x!=y calls x.__ne__(y), x>y calls x.__gt__(y), and x>=y calls x.__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 and True 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 call bool() on the value to determine if the result is true or false.

关于python - 在 Python 中,说我们 "override"内置运算符的行为准确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42863355/

相关文章:

python - 更改反射(reflect)在订单摘要中错误项目中的变体数量

python - 数学表达式的解析 Sphinx/imgmath

python - 序列输出循环 - python

java - 引用变量的封装?

C++ 复制构造函数和 = 运算符重载

python - 重新排序 numpy ndarray 的最后一个维度

javascript - 在另一个函数 JavaScript/JQuery 中调用函数的最佳方法?

java - 为什么包含主要方法的类没有实例化并且在Java中仍然可以?

C++ 运算符和参数

c++ - 数组订阅 : returning Reference vs proxy class method