Difference between operators and methods

后端 未结 3 411
我寻月下人不归
我寻月下人不归 2021-01-06 07:59

Is there any substantial difference between operators and methods?

The only difference I see is the way the are called, do they have other differences?

For

3条回答
  •  囚心锁ツ
    2021-01-06 08:41

    Is there any substantial difference between operators and methods?

    Practically speaking, there is no difference because each operator is mapped to a specific Python special method. Moreover, whenever Python encounters the use of an operator, it calls its associated special method implicitly. For example:

    1 + 2
    

    implicitly calls int.__add__, which makes the above expression equivalent1 to:

    (1).__add__(2)
    

    Below is a demonstration:

    >>> class Foo:
    ...     def __add__(self, other):
    ...         print("Foo.__add__ was called")
    ...         return other + 10
    ...
    >>> f = Foo()
    >>> f + 1
    Foo.__add__ was called
    11
    >>> f.__add__(1)
    Foo.__add__ was called
    11
    >>>
    

    Of course, actually using (1).__add__(2) in place of 1 + 2 would be inefficient (and ugly!) because it involves an unnecessary name lookup with the . operator.

    That said, I do not see a problem with generally regarding the operator symbols (+, -, *, etc.) as simply shorthands for their associated method names (__add__, __sub__, __mul__, etc.). After all, they each end up doing the same thing by calling the same method.


    1Well, roughly equivalent. As documented here, there is a set of special methods prefixed with the letter r that handle reflected operands. For example, the following expression:

    A + B
    

    may actually be equivalent to:

    B.__radd__(A)
    

    if A does not implement __add__ but B implements __radd__.

提交回复
热议问题