Using __add__ operator with multiple arguments in Python

后端 未结 4 1854
你的背包
你的背包 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:52

    you could always just do this:

    >>> class A:
    ...     def __init__(self, val):
    ...         self.val = val
    ...     def __repr__(self):
    ...         return f''
    ...     def __add__(self, other):
    ...         print(f'Summing {self} + {other}')
    ...         return A(self.val + other)
    ...
    >>> A(42) + 10
    Summing A(42) + 10
    
    >>> A(42) + 10 + 100
    Summing A(42) + 10
    Summing A(52) + 100
    >>> class A:
    ...     def __init__(self, val):
    ...         self.val = val
    ...     def __repr__(self):
    ...         return f''
    ...     def __add__(self, other):
    ...         print(f'Summing {self} + {other}')
    ...         return A(self.val + other)
    ...
    >>> A(42) + 10
    Summing A(42) + 10
    
    >>> A(42) + 10 + 100
    Summing A(42) + 10
    Summing A(52) + 100
    
    

提交回复
热议问题