Python23.5_运算符重载、序列与切片

本文探讨Python中的运算符重载,详细解释了__add__、__radd__、__iadd__的区别,以及它们在运算过程中的行为。同时,介绍了__repr__和__str__方法的作用,明确了两者在输出表示上的差异。此外,文章还讲解了序列的概念,阐述了如何使对象成为序列以及切片操作的工作原理。
摘要由CSDN通过智能技术生成

运算符重载

from math import hypot,sqrt
class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        """
        加法重载
        :param other:
        :return:
        """
        x = self.x + other.x
        y = self.y + other.y
        return Vector2D(x, y)

    def __str__(self):
        return "Vector2D(x = {},y = {})".format(self.x, self.y)

    def __sub__(self, other):
        """
        减法重载
        :param other:
        :return:
        """
        x = self.x - other.x
        y = self.y - other.y
        return Vector2D(x, y)

    def __mul__(self, other):
        """
        乘法重载
        :param other:
        :return:
        """
        x = self.x * other.x
        y = self.y * other.y
        return Vector2D(x, y
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值