题解 | #重载运算#

重载运算

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

class Coordinate:
    def __init__(self,x,y) -> None:
        self.x = x
        self.y = y
    
    def __str__(self) -> str:
        return(f'({self.x}, {self.y})')
    
    def __add__(self,other):
        return Coordinate(self.x + other.x,self.y + other.y)

a, b = input().split()
c, d = input().split()

c1 = Coordinate(int(a),int(b))
c2 = Coordinate(int(c),int(d))
print(c1.__add__(c2))

__add__:特殊方法,定义了如何对两个 Coordinate 实例进行加法操作。

  1. self:这是当前类的实例的引用。
  2. other:这是要与 self 实例相加的对象。

在Python中,重载运算符意味着你可以定义类的特殊方法来改变内置运算符(如 +, -, *, /, ==, <, 等等)的行为,使得它们可以作用于类的实例。这通常通过在类定义中实现相应的特殊方法(也称为魔术方法)来完成。

以下是一些常见的运算符重载方法:

  • __add__(self, other): 重载 + 运算符。
  • __sub__(self, other): 重载 - 运算符。
  • __mul__(self, other): 重载 * 运算符。
  • __truediv__(self, other): 重载 / 运算符(Python 3中)。
  • __floordiv__(self, other): 重载 // 运算符。
  • __mod__(self, other): 重载 % 运算符。
  • __pow__(self, other[, modulo]): 重载 ** 运算符。
全部评论

相关推荐

零OFFER战士:另一个版本查看图片
点赞 评论 收藏
分享
一表renzha:手写数字识别就是一个作业而已
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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