题解 | #重载运算#

重载运算

https://www.nowcoder.com/practice/342d1b8b0fe3416797bad62d22cbb51a

num_list_1 = input().split()
x1 = int(num_list_1[0])
y1 = int(num_list_1[1])
num_list_2 = input().split()
x2 = int(num_list_2[0])
y2 = int(num_list_2[1])


class Coordinate(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __str__(self):
        return f"({self.x}, {self.y})"
    
    def __add__(self, other):
        return Coordinate(self.x + other.x, self.y + other.y)


c1 = Coordinate(x1, y1)
c2 = Coordinate(x2, y2)
c = c1.__add__(c2)
print(c)

Python中的__str__方法:

  1. 使用print输出实例对象变量时,默认情况下会输出是由哪个类创建的实例对象以及在内存中的地址
  2. 实际开发中,如果想要打印自定义的内容,可重写__str__方法,该方法必须返回一个字符串

Python中的__add__方法:

其中,self为c1 other为c2 __add__方法return的是一个新的实例对象c

因为重写了__str__方法,此时print(c)输出的就不再是由哪个类创建的实例对象以及在内存中的地址,而是在__str__方法中自定义的输出内容。

#Python学旅#
全部评论

相关推荐

uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
昨天 16:13
嘉应学院 Python
xiaolihuam...:很明显骗子,如果是hr直接约你面试了,哪用得着内推,如果是员工的话,你得多优秀,一线员工直接加你微信,
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务