[Python] [4] 类中的魔术方法(2)

前言

看完我的上篇文章,各位应该都对魔术方法(特殊方法)有了初步的认识吧!

那么这期,我们还是围绕 Number 类展开探究

Number 类代码

上期,我们的 Number 类代码发展成了这样:

class Number:
    """一次模拟数字的简单尝试"""

    def __init__(self, value):
        """Number 对象有 value 属性"""
        self.value = value

    def __str__(self):
        """Number 对象的字符串形式"""
        return str(self.value)

    def __add__(self, other: int | float or "Number"):
        return Number(self.value + other.value if isinstance(other, Number)
                      else self.value + other)

    def __radd__(self, other: int | float or "Number"):
        return Number(other.value + self.value if isinstance(other, Number)
                      else other + self.value)

    def __sub__(self, other: int | float or "Number"):
        return Number(self.value - other.value if isinstance(other, Number)
                      else self.value - other)

    def __rsub__(self, other: int | float or "Number"):
        return Number(other.value - self.value if isinstance(other, Number)
                      else other - self.value)

那么这期,我们就来接着完善它吧!

__iadd__

这个特殊方法和 __add__ 很像,大家猜猜它是干什么的?

bingo! 它是用来支持增量运算符 "+=" 的!

一般人可能会想在 __iadd__中直接修改属性的值

但这是不对的

我们照常返回期望的值就好了!

python 会帮我们完成赋值

所以,一般来说只要照搬 __add__ 就 OK 了

    def __iadd__(self, other: int | float or "Number"):
        return Number(self.value + other.value if isinstance(other, Number)
                      else self.value + other)
n1 = Number(10)
n1 += 10
n1.value == 20  # Ture
__isub__

既然 __iadd__ 会了,那这个也不成问题了!

    def __isub__(self, other: int | float or "Number"):
        return Number(self.value - other.value if isinstance(other, Number)
                      else self.value - other)
结尾

那么今天的python就分享到这

本文只面向初学者

作者是一名12岁的小学生

所以不喜勿喷

如有错误还望指出!

你们的支持是我的最大动力!

还想了解什么就发在评论区吧!

下周见!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值