预计阅读本页时间:-
In-Place Addition
To also implement += in-place augmented addition, code either an __iadd__ or an __add__. The latter is used if the former is absent. In fact, the prior section’s Commuter class supports += already for this reason, but __iadd__ allows for more efficient in-place changes:
>>> class Number:
... def __init__(self, val):
... self.val = val
... def __iadd__(self, other): # __iadd__ explicit: x += y
... self.val += other # Usually returns self
... return self
...
>>> x = Number(5)
>>> x += 1
>>> x += 1
>>> x.val
7
>>> class Number:
... def __init__(self, val):
... self.val = val
... def __add__(self, other): # __add__ fallback: x = (x + y)
... return Number(self.val + other) # Propagates class type
...
>>> x = Number(5)
>>> x += 1
>>> x += 1
>>> x.val
7
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
Every binary operator has similar right-side and in-place overloading methods that work the same (e.g., __mul__, __rmul__, and __imul__). Right-side methods are an advanced topic and tend to be fairly rarely used in practice; you only code them when you need operators to be commutative, and then only if you need to support such operators at all. For instance, a Vector class may use these tools, but an Employee or Button class probably would not.