Using __add__ operator with multiple arguments in Python

后端 未结 4 1853
你的背包
你的背包 2021-01-05 10:07

I am trying to add a class object with a number, but I\'m confused on how to go about adding a class object with two numbers. For example, this is my hypothetical ad

相关标签:
4条回答
  • 2021-01-05 10:34

    No, you can't use multiple arguments. Python executes each + operator separately, the two + operators are distinct expressions.

    For your example, object + 1 + 2 really is (object + 1) + 2. If (object + 1) produces an object that has an __add__ method, then Python will call that method for the second operator.

    You could, for example, return another instance of A here:

    >>> class A:
    ...     def __init__(self, val):
    ...         self.val = val
    ...     def __repr__(self):
    ...         return f'<A({self.val})>'
    ...     def __add__(self, other):
    ...         print(f'Summing {self} + {other}')
    ...         return A(self.val + other)
    ...
    >>> A(42) + 10
    Summing A(42) + 10
    <A(52)>
    >>> A(42) + 10 + 100
    Summing A(42) + 10
    Summing A(52) + 100
    <A(152)>
    
    0 讨论(0)
  • 2021-01-05 10:40

    You would want your return value to be an object itself, that also supports the add operation, e.g.:

    class A:
        def __init__(self, value=0):
            self.value = value
    
        def __add__(self, b):
            return A(self.value + b)
    
        def __str__(self):
            return str(self.value)
    
    a = A()
    print(a + 1 + 2)
    

    Output:

    3

    0 讨论(0)
  • 2021-01-05 10:52

    you could always just do this:

    >>> class A:
    ...     def __init__(self, val):
    ...         self.val = val
    ...     def __repr__(self):
    ...         return f'<A({self.val})>'
    ...     def __add__(self, other):
    ...         print(f'Summing {self} + {other}')
    ...         return A(self.val + other)
    ...
    >>> A(42) + 10
    Summing A(42) + 10
    <A(52)>
    >>> A(42) + 10 + 100
    Summing A(42) + 10
    Summing A(52) + 100
    <A(152)>>>> class A:
    ...     def __init__(self, val):
    ...         self.val = val
    ...     def __repr__(self):
    ...         return f'<A({self.val})>'
    ...     def __add__(self, other):
    ...         print(f'Summing {self} + {other}')
    ...         return A(self.val + other)
    ...
    >>> A(42) + 10
    Summing A(42) + 10
    <A(52)>
    >>> A(42) + 10 + 100
    Summing A(42) + 10
    Summing A(52) + 100
    <A(152)>
    
    0 讨论(0)
  • 2021-01-05 10:56

    It perfectly works even with multiple values since each add only adds two values (see the multiple + signs when you ad multiple values):

    class A:
        def __init__(self, value):
            self.a = value
        def __add__(self, another_value):
            return self.a + another_value
    
    
    a = A(1)
    print(a+1+1)
    
    0 讨论(0)
提交回复
热议问题