Using __add__ operator with multiple arguments in Python

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

提交回复
热议问题