TypeError after overriding the __add__ method

后端 未结 5 1982
时光说笑
时光说笑 2020-11-29 03:33

I am trying to understand how __add__ works:

class MyNum:
    def __init__(self,num):
        self.num=num
    def __add__(self,other):
                 


        
5条回答
  •  广开言路
    2020-11-29 03:59

    >>> help(sum)
    Help on built-in function sum in module __builtin__:
    
    sum(...)
        sum(sequence[, start]) -> value
    
        Returns the sum of a sequence of numbers (NOT strings) plus the value
        of parameter 'start' (which defaults to 0).  When the sequence is
        empty, returns start.
    

    In other words, provide a start value:

    sum(d, MyNum(0))
    

    Edit pasted from my below comment:

    sum works with a default start value of the integer zero. Your MyNum class as written does not know how to add itself to integers. To solve this you have two options. Either you can provide a start value to sum that has the same type as you class, or you can implement __radd__, which Python calls when adding values of differing types (such as when the first value in d is added to the default start value of zero).

提交回复
热议问题