Python正確重載運(yùn)算符的方法示例詳解
前言
說到運(yùn)算符重載相信大家都不陌生,運(yùn)算符重載的作用是讓用戶定義的對象使用中綴運(yùn)算符(如 + 和 |)或一元運(yùn)算符(如 - 和 ~)。說得寬泛一些,在 Python 中,函數(shù)調(diào)用(())、屬性訪問(.)和元素訪問 / 切片([])也是運(yùn)算符。
我們?yōu)?Vector 類簡略實(shí)現(xiàn)了幾個運(yùn)算符。__add__ 和 __mul__ 方法是為了展示如何使用特殊方法重載運(yùn)算符,不過有些小問題被我們忽視了。此外,我們定義的Vector2d.__eq__
方法認(rèn)為 Vector(3, 4) == [3, 4]
是真的(True),這可能并不合理。下面來一起看看詳細(xì)的介紹吧。
運(yùn)算符重載基礎(chǔ)
在某些圈子中,運(yùn)算符重載的名聲并不好。這個語言特性可能(已經(jīng))被濫用,讓程序員困惑,導(dǎo)致缺陷和意料之外的性能瓶頸。但是,如果使用得當(dāng),API 會變得好用,代碼會變得易于閱讀。Python 施加了一些限制,做好了靈活性、可用性和安全性方面的平衡:
- 不能重載內(nèi)置類型的運(yùn)算符
- 不能新建運(yùn)算符,只能重載現(xiàn)有的
- 某些運(yùn)算符不能重載——is、and、or 和 not(不過位運(yùn)算符
- &、| 和 ~ 可以)
前面的博文已經(jīng)為 Vector 定義了一個中綴運(yùn)算符,即 ==,這個運(yùn)算符由__eq__ 方法支持。我們將改進(jìn) __eq__ 方法的實(shí)現(xiàn),更好地處理不是Vector 實(shí)例的操作數(shù)。然而,在運(yùn)算符重載方面,眾多比較運(yùn)算符(==、!=、>、<、>=、<=)是特例,因此我們首先將在 Vector 中重載四個算術(shù)運(yùn)算符:一元運(yùn)算符 - 和 +,以及中綴運(yùn)算符 + 和 *。
一元運(yùn)算符
-(__neg__)
一元取負(fù)算術(shù)運(yùn)算符。如果 x 是 -2,那么 -x == 2。
+(__pos__)
一元取正算術(shù)運(yùn)算符。通常,x == +x,但也有一些例外。如果好奇,請閱讀“x 和 +x 何時不相等”附注欄。
~(__invert__)
對整數(shù)按位取反,定義為 ~x == -(x+1)。如果 x 是 2,那么 ~x== -3。
支持一元運(yùn)算符很簡單,只需實(shí)現(xiàn)相應(yīng)的特殊方法。這些特殊方法只有一個參數(shù),self。然后,使用符合所在類的邏輯實(shí)現(xiàn)。不過,要遵守運(yùn)算符的一個基本規(guī)則:始終返回一個新對象。也就是說,不能修改self,要創(chuàng)建并返回合適類型的新實(shí)例。
對 - 和 + 來說,結(jié)果可能是與 self 同屬一類的實(shí)例。多數(shù)時候,+ 最好返回 self 的副本。abs(...) 的結(jié)果應(yīng)該是一個標(biāo)量。但是對 ~ 來說,很難說什么結(jié)果是合理的,因?yàn)榭赡懿皇翘幚碚麛?shù)的位,例如在ORM 中,SQL WHERE 子句應(yīng)該返回反集。
def __abs__(self): return math.sqrt(sum(x * x for x in self)) def __neg__(self): return Vector(-x for x in self) #為了計算 -v,構(gòu)建一個新 Vector 實(shí)例,把 self 的每個分量都取反 def __pos__(self): return Vector(self) #為了計算 +v,構(gòu)建一個新 Vector 實(shí)例,傳入 self 的各個分量
x 和 +x 何時不相等
每個人都覺得 x == +x,而且在 Python 中,幾乎所有情況下都是這樣。但是,我在標(biāo)準(zhǔn)庫中找到兩例 x != +x 的情況。
第一例與 decimal.Decimal
類有關(guān)。如果 x 是 Decimal 實(shí)例,在算術(shù)運(yùn)算的上下文中創(chuàng)建,然后在不同的上下文中計算 +x,那么 x!= +x。例如,x 所在的上下文使用某個精度,而計算 +x 時,精度變了,例如下面的 🌰
算術(shù)運(yùn)算上下文的精度變化可能導(dǎo)致 x 不等于 +x
>>> import decimal >>> ctx = decimal.getcontext() #獲取當(dāng)前全局算術(shù)運(yùn)算符的上下文引用 >>> ctx.prec = 40 #把算術(shù)運(yùn)算上下文的精度設(shè)為40 >>> one_third = decimal.Decimal('1') / decimal.Decimal('3') #使用當(dāng)前精度計算1/3 >>> one_third Decimal('0.3333333333333333333333333333333333333333') #查看結(jié)果,小數(shù)點(diǎn)后的40個數(shù)字 >>> one_third == +one_third #one_third = +one_thied返回TRUE True >>> ctx.prec = 28 #把精度降為28 >>> one_third == +one_third #one_third = +one_thied返回FalseFalse >>> +one_third Decimal('0.3333333333333333333333333333') #查看+one_third,小術(shù)后的28位數(shù)字
雖然每個 +one_third 表達(dá)式都會使用 one_third 的值創(chuàng)建一個新 Decimal 實(shí)例,但是會使用當(dāng)前算術(shù)運(yùn)算上下文的精度。
x != +x 的第二例在 collections.Counter 的文檔中(https://docs.python.org/3/library/collections.html#collections.Counter)。類實(shí)現(xiàn)了幾個算術(shù)運(yùn)算符,例如中綴運(yùn)算符 +,作用是把兩個Counter 實(shí)例的計數(shù)器加在一起。然而,從實(shí)用角度出發(fā),Counter 相加時,負(fù)值和零值計數(shù)會從結(jié)果中剔除。而一元運(yùn)算符 + 等同于加上一個空 Counter,因此它產(chǎn)生一個新的Counter 且僅保留大于零的計數(shù)器。
🌰 一元運(yùn)算符 + 得到一個新 Counter 實(shí)例,但是沒有零值和負(fù)值計數(shù)器
>>> from collections import Counter >>> ct = Counter('abracadabra') >>> ct['r'] = -3 >>> ct['d'] = 0 >>> ct Counter({'a': 5, 'r': -3, 'b': 2, 'c': 1, 'd': 0}) >>> +ct Counter({'a': 5, 'b': 2, 'c': 1})
重載向量加法運(yùn)算符+
兩個歐幾里得向量加在一起得到的是一個新向量,它的各個分量是兩個向量中相應(yīng)的分量之和。比如說:
>>> v1 = Vector([3, 4, 5]) >>> v2 = Vector([6, 7, 8]) >>> v1 + v2 Vector([9.0, 11.0, 13.0]) >>> v1 + v2 == Vector([3+6, 4+7, 5+8]) True
確定這些基本的要求之后,__add__ 方法的實(shí)現(xiàn)短小精悍,🌰 如下
def __add__(self, other): pairs = itertools.zip_longest(self, other, fillvalue=0.0) #生成一個元祖,a來自self,b來自other,如果兩個長度不夠,通過fillvalue設(shè)置的補(bǔ)全值自動補(bǔ)全短的 return Vector(a + b for a, b in pairs) #使用生成器表達(dá)式計算pairs中的各個元素的和
還可以把Vector 加到元組或任何生成數(shù)字的可迭代對象上:
# 在Vector類中定義 def __add__(self, other): pairs = itertools.zip_longest(self, other, fillvalue=0.0) #生成一個元祖,a來自self,b來自other,如果兩個長度不夠,通過fillvalue設(shè)置的補(bǔ)全值自動補(bǔ)全短的 return Vector(a + b for a, b in pairs) #使用生成器表達(dá)式計算pairs中的各個元素的和 def __radd__(self, other): #會直接委托給__add__ return self + other
__radd__ 通常就這么簡單:直接調(diào)用適當(dāng)?shù)倪\(yùn)算符,在這里就是委托__add__。任何可交換的運(yùn)算符都能這么做。處理數(shù)字和向量時,+ 可以交換,但是拼接序列時不行。
重載標(biāo)量乘法運(yùn)算符*
Vector([1, 2, 3]) * x 是什么意思?如果 x 是數(shù)字,就是計算標(biāo)量積(scalar product),結(jié)果是一個新 Vector 實(shí)例,各個分量都會乘以x——這也叫元素級乘法(elementwise multiplication)。
>>> v1 = Vector([1, 2, 3]) >>> v1 * 10 Vector([10.0, 20.0, 30.0]) >>> 11 * v1 Vector([11.0, 22.0, 33.0])
涉及 Vector 操作數(shù)的積還有一種,叫兩個向量的點(diǎn)積(dotproduct);如果把一個向量看作 1×N 矩陣,把另一個向量看作 N×1 矩陣,那么就是矩陣乘法。NumPy 等庫目前的做法是,不重載這兩種意義的 *,只用 * 計算標(biāo)量積。例如,在 NumPy 中,點(diǎn)積使用numpy.dot()
函數(shù)計算。
回到標(biāo)量積的話題。我們依然先實(shí)現(xiàn)最簡可用的 __mul__ 和 __rmul__方法:
def __mul__(self, scalar): if isinstance(scalar, numbers.Real): return Vector(n * scalar for n in self) else: return NotImplemented def __rmul__(self, scalar): return self * scalar
這兩個方法確實(shí)可用,但是提供不兼容的操作數(shù)時會出問題。scalar參數(shù)的值要是數(shù)字,與浮點(diǎn)數(shù)相乘得到的積是另一個浮點(diǎn)數(shù)(因?yàn)閂ector 類在內(nèi)部使用浮點(diǎn)數(shù)數(shù)組)。因此,不能使用復(fù)數(shù),但可以是int、bool(int 的子類),甚至 fractions.Fraction
實(shí)例等標(biāo)量。
提供了點(diǎn)積所需的 @ 記號(例如,a @ b 是 a 和 b 的點(diǎn)積)。@ 運(yùn)算符由特殊方法 __matmul__、__rmatmul__ 和__imatmul__ 提供支持,名稱取自“matrix multiplication”(矩陣乘法)
>>> va = Vector([1, 2, 3]) >>> vz = Vector([5, 6, 7]) >>> va @ vz == 38.0 # 1*5 + 2*6 + 3*7 True >>> [10, 20, 30] @ vz 380.0 >>> va @ 3 Traceback (most recent call last): ... TypeError: unsupported operand type(s) for @: 'Vector' and 'int'
下面是相應(yīng)特殊方法的代碼:
>>> va = Vector([1, 2, 3]) >>> vz = Vector([5, 6, 7]) >>> va @ vz == 38.0 # 1*5 + 2*6 + 3*7 True >>> [10, 20, 30] @ vz 380.0 >>> va @ 3 Traceback (most recent call last): ... TypeError: unsupported operand type(s) for @: 'Vector' and 'int'
眾多比較運(yùn)算符
Python 解釋器對眾多比較運(yùn)算符(==、!=、>、<、>=、<=)的處理與前文類似,不過在兩個方面有重大區(qū)別。
- 正向和反向調(diào)用使用的是同一系列方法。例如,對 == 來說,正向和反向調(diào)用都是 __eq__ 方法,只是把參數(shù)對調(diào)了;而正向的 __gt__ 方法調(diào)用的是反向的 __lt__方法,并把參數(shù)對調(diào)。
- 對 == 和 != 來說,如果反向調(diào)用失敗,Python 會比較對象的 ID,而不拋出 TypeError。
眾多比較運(yùn)算符:正向方法返回NotImplemented的話,調(diào)用反向方法
|
中綴運(yùn)算符 |
正向方法調(diào)用 |
反向方法調(diào)用 |
后備機(jī)制 |
相等性 |
a == b |
a.__eq__(b) |
b.__eq__(a) |
返回 id(a) == id(b) |
|
a != b |
a.__ne__(b) |
b.__ne__(a) |
返回 not (a == b) |
排序 |
a > b |
a.__gt__(b) |
b.__lt__(a) |
拋出 TypeError |
|
a < b |
a.__lt__(b) |
b.__gt__(a) |
拋出 TypeError |
|
a >= b |
a.__ge__(b) |
b.__le__(a) |
拋出 TypeError |
|
a <= b |
a.__le__(b) |
b.__ge__(a) |
拋出T ypeError |
看下面的🌰
from array import array import reprlib import math import numbers import functools import operator import itertools class Vector: typecode = 'd' def __init__(self, components): self._components = array(self.typecode, components) def __iter__(self): return iter(self._components) def __repr__(self): components = reprlib.repr(self._components) components = components[components.find('['):-1] return 'Vector({})'.format(components) def __str__(self): return str(tuple(self)) def __bytes__(self): return (bytes([ord(self.typecode)]) + bytes(self._components)) def __eq__(self, other): return (len(self) == len(other) and all(a == b for a, b in zip(self, other))) def __hash__(self): hashes = map(hash, self._components) return functools.reduce(operator.xor, hashes, 0) def __add__(self, other): pairs = itertools.zip_longest(self, other, fillvalue=0.0) #生成一個元祖,a來自self,b來自other,如果兩個長度不夠,通過fillvalue設(shè)置的補(bǔ)全值自動補(bǔ)全短的 return Vector(a + b for a, b in pairs) #使用生成器表達(dá)式計算pairs中的各個元素的和 def __radd__(self, other): #會直接委托給__add__ return self + other def __mul__(self, scalar): if isinstance(scalar, numbers.Real): return Vector(n * scalar for n in self) else: return NotImplemented def __rmul__(self, scalar): return self * scalar def __matmul__(self, other): try: return sum(a * b for a, b in zip(self, other)) except TypeError: return NotImplemented def __rmatmul__(self, other): return self @ other def __abs__(self): return math.sqrt(sum(x * x for x in self)) def __neg__(self): return Vector(-x for x in self) #為了計算 -v,構(gòu)建一個新 Vector 實(shí)例,把 self 的每個分量都取反 def __pos__(self): return Vector(self) #為了計算 +v,構(gòu)建一個新 Vector 實(shí)例,傳入 self 的各個分量 def __bool__(self): return bool(abs(self)) def __len__(self): return len(self._components) def __getitem__(self, index): cls = type(self) if isinstance(index, slice): return cls(self._components[index]) elif isinstance(index, numbers.Integral): return self._components[index] else: msg = '{.__name__} indices must be integers' raise TypeError(msg.format(cls)) shorcut_names = 'xyzt' def __getattr__(self, name): cls = type(self) if len(name) == 1: pos = cls.shorcut_names.find(name) if 0 <= pos < len(self._components): return self._components[pos] msg = '{.__name__!r} object has no attribute {!r}' raise AttributeError(msg.format(cls, name)) def angle(self, n): r = math.sqrt(sum(x * x for x in self[n:])) a = math.atan2(r, self[n-1]) if (n == len(self) - 1 ) and (self[-1] < 0): return math.pi * 2 - a else: return a def angles(self): return (self.angle(n) for n in range(1, len(self))) def __format__(self, fmt_spec=''): if fmt_spec.endswith('h'): fmt_spec = fmt_spec[:-1] coords = itertools.chain([abs(self)], self.angles()) outer_fmt = '<{}>' else: coords = self outer_fmt = '({})' components = (format(c, fmt_spec) for c in coords) return outer_fmt.format(', '.join(components)) @classmethod def frombytes(cls, octets): typecode = chr(octets[0]) memv = memoryview(octets[1:]).cast(typecode) return cls(memv) va = Vector([1.0, 2.0, 3.0]) vb = Vector(range(1, 4)) print('va == vb:', va == vb) #兩個具有相同數(shù)值分量的 Vector 實(shí)例是相等的 t3 = (1, 2, 3) print('va == t3:', va == t3) print('[1, 2] == (1, 2):', [1, 2] == (1, 2))
上面代碼執(zhí)行返回的結(jié)果為:
va == vb: True va == t3: True [1, 2] == (1, 2): False
從 Python 自身來找線索,我們發(fā)現(xiàn) [1,2] == (1, 2)
的結(jié)果是False。因此,我們要保守一點(diǎn),做些類型檢查。如果第二個操作數(shù)是Vector 實(shí)例(或者 Vector 子類的實(shí)例),那么就使用 __eq__ 方法的當(dāng)前邏輯。否則,返回 NotImplemented,讓 Python 處理。
🌰 vector_v8.py:改進(jìn) Vector 類的 __eq__ 方法
def __eq__(self, other): if isinstance(other, Vector): #判斷對比的是否和Vector同屬一個實(shí)例 return (len(self) == len(other) and all(a == b for a, b in zip(self, other))) else: return NotImplemented #否則,返回NotImplemented
改進(jìn)以后的代碼執(zhí)行結(jié)果:
>>> va = Vector([1.0, 2.0, 3.0]) >>> vb = Vector(range(1, 4)) >>> va == vb True >>> t3 = (1, 2, 3) >>> va == t3 False
增量賦值運(yùn)算符
Vector 類已經(jīng)支持增量賦值運(yùn)算符 += 和 *= 了,示例如下
🌰 增量賦值不會修改不可變目標(biāo),而是新建實(shí)例,然后重新綁定
>>> v1 = Vector([1, 2, 3]) >>> v1_alias = v1 # 復(fù)制一份,供后面審查Vector([1, 2, 3])對象 >>> id(v1) # 記住一開始綁定給v1的Vector實(shí)例的ID >>> v1 += Vector([4, 5, 6]) # 增量加法運(yùn)算 >>> v1 # 結(jié)果與預(yù)期相符 Vector([5.0, 7.0, 9.0]) >>> id(v1) # 但是創(chuàng)建了新的Vector實(shí)例 >>> v1_alias # 審查v1_alias,確認(rèn)原來的Vector實(shí)例沒被修改 Vector([1.0, 2.0, 3.0]) >>> v1 *= 11 # 增量乘法運(yùn)算 >>> v1 # 同樣,結(jié)果與預(yù)期相符,但是創(chuàng)建了新的Vector實(shí)例 Vector([55.0, 77.0, 99.0]) >>> id(v1)
完整代碼:
from array import array import reprlib import math import numbers import functools import operator import itertools class Vector: typecode = 'd' def __init__(self, components): self._components = array(self.typecode, components) def __iter__(self): return iter(self._components) def __repr__(self): components = reprlib.repr(self._components) components = components[components.find('['):-1] return 'Vector({})'.format(components) def __str__(self): return str(tuple(self)) def __bytes__(self): return (bytes([ord(self.typecode)]) + bytes(self._components)) def __eq__(self, other): if isinstance(other, Vector): return (len(self) == len(other) and all(a == b for a, b in zip(self, other))) else: return NotImplemented def __hash__(self): hashes = map(hash, self._components) return functools.reduce(operator.xor, hashes, 0) def __add__(self, other): pairs = itertools.zip_longest(self, other, fillvalue=0.0) return Vector(a + b for a, b in pairs) def __radd__(self, other): return self + other def __mul__(self, scalar): if isinstance(scalar, numbers.Real): return Vector(n * scalar for n in self) else: return NotImplemented def __rmul__(self, scalar): return self * scalar def __matmul__(self, other): try: return sum(a * b for a, b in zip(self, other)) except TypeError: return NotImplemented def __rmatmul__(self, other): return self @ other def __abs__(self): return math.sqrt(sum(x * x for x in self)) def __neg__(self): return Vector(-x for x in self) def __pos__(self): return Vector(self) def __bool__(self): return bool(abs(self)) def __len__(self): return len(self._components) def __getitem__(self, index): cls = type(self) if isinstance(index, slice): return cls(self._components[index]) elif isinstance(index, numbers.Integral): return self._components[index] else: msg = '{.__name__} indices must be integers' raise TypeError(msg.format(cls)) shorcut_names = 'xyzt' def __getattr__(self, name): cls = type(self) if len(name) == 1: pos = cls.shorcut_names.find(name) if 0 <= pos < len(self._components): return self._components[pos] msg = '{.__name__!r} object has no attribute {!r}' raise AttributeError(msg.format(cls, name)) def angle(self, n): r = math.sqrt(sum(x * x for x in self[n:])) a = math.atan2(r, self[n-1]) if (n == len(self) - 1 ) and (self[-1] < 0): return math.pi * 2 - a else: return a def angles(self): return (self.angle(n) for n in range(1, len(self))) def __format__(self, fmt_spec=''): if fmt_spec.endswith('h'): fmt_spec = fmt_spec[:-1] coords = itertools.chain([abs(self)], self.angles()) outer_fmt = '<{}>' else: coords = self outer_fmt = '({})' components = (format(c, fmt_spec) for c in coords) return outer_fmt.format(', '.join(components)) @classmethod def frombytes(cls, octets): typecode = chr(octets[0]) memv = memoryview(octets[1:]).cast(typecode) return cls(memv)
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Python機(jī)器學(xué)習(xí)NLP自然語言處理基本操作之京東評論分類
自然語言處理( Natural Language Processing, NLP)是計算機(jī)科學(xué)領(lǐng)域與人工智能領(lǐng)域中的一個重要方向。它研究能實(shí)現(xiàn)人與計算機(jī)之間用自然語言進(jìn)行有效通信的各種理論和方法2021-10-10在win和Linux系統(tǒng)中python命令行運(yùn)行的不同
本文給大家分享的是作者在在win和Linux系統(tǒng)中python命令行運(yùn)行的不同的解決方法,有相同需求的小伙伴可以參考下2016-07-07Python實(shí)現(xiàn)socket非阻塞通訊功能示例
這篇文章主要介紹了Python實(shí)現(xiàn)socket非阻塞通訊功能,結(jié)合實(shí)例形式分析了Python使用socket模塊進(jìn)行非阻塞通訊的原理、多線程及客戶端、服務(wù)器端相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-11-11使用python實(shí)現(xiàn)一個簡單ping?pong服務(wù)器
這篇文章主要為大家介紹了使用python實(shí)現(xiàn)一個簡單ping?pong服務(wù)器,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04使用OpenCV-python3實(shí)現(xiàn)滑動條更新圖像的Canny邊緣檢測功能
這篇文章主要介紹了使用OpenCV-python3實(shí)現(xiàn)滑動條更新圖像的Canny邊緣檢測功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12Pygame實(shí)戰(zhàn)練習(xí)之推箱子游戲
推箱子想必是很多人童年時期的經(jīng)典游戲,我們依舊能記得抱個老人機(jī)娛樂的場景,下面這篇文章主要給大家介紹了關(guān)于如何利用python寫一個簡單的推箱子小游戲的相關(guān)資料,需要的朋友可以參考下2021-09-09Python實(shí)現(xiàn)統(tǒng)計圖像連通域的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何利用Python實(shí)現(xiàn)統(tǒng)計圖像連通域的功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-04-04Python tkinter之Bind(綁定事件)的使用示例
這篇文章主要介紹了Python tkinter之Bind(綁定事件)的使用詳解,幫助大家更好的理解和學(xué)習(xí)python的gui開發(fā),感興趣的朋友可以了解下2021-02-02