开发者

Python Class, add 2D points

how can you add two values using __add__ function

(1,2)+(2,3) = (3,5)



def __add__(self, other):
    return Point((la开发者_运维问答mbda x,y:x+y),self,other)

is this the way to think? What is the probable error!!


That's close, except you need to return NotImplemented if it's not a Point:

def __add__(self, other):
    if not isinstance(other, Point):
        return NotImplemented
    return Point(self.x + other.x, self.y + other.y)


If I'm understanding you correctly, I would probably do it this way:

def __add__(self, other):
    return Point(self.x + other.x, self.y + other.y)

Your question is a bit vague and you don't provide details about the Point class so it's a bit difficult to understand exactly what you're asking.

Specifically, I don't understand the purpose of the lambda argument to the constructor. I think I understand what it's doing, but I'm not sure I can see a situation in which that constructor would be a useful way to express an operation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜