Using an operator to add in Python

前端 未结 5 2183
隐瞒了意图╮
隐瞒了意图╮ 2021-01-06 13:35

Consider:

operator.add(a, b)

I\'m having trouble understanding what this does. An operator is something like +-*/, so what doe

5条回答
  •  长情又很酷
    2021-01-06 13:47

    It literally is how the + operator is defined. Look at the following example

    class foo():
        def __init__(self, a):
            self.a = a
        def __add__(self, b):
            return self.a + b
    
    >>> x = foo(5)
    >>> x + 3
    8
    

    The + operator actually just calls the __add__ method of the class

    The same thing happens for native Python types,

    >>> 5 + 3
    8
    >>> operator.add(5,3)
    8
    

    Note that since I defined my __add__ method, I can also do

    >>> operator.add(x, 3)
    8
    

提交回复
热议问题