前言
看完我的上篇文章,各位应该都对魔术方法(特殊方法)有了初步的认识吧!
那么这期,我们还是围绕 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岁的小学生
所以不喜勿喷
如有错误还望指出!
你们的支持是我的最大动力!
还想了解什么就发在评论区吧!
下周见!