Python中的數(shù)學(xué)運(yùn)算操作符使用進(jìn)階
Python中對象的行為是由它的類型 (Type) 決定的。所謂類型就是支持某些特定的操作。數(shù)字對象在任何編程語言中都是基礎(chǔ)元素,支持加、減、乘、除等數(shù)學(xué)操作。
Python的數(shù)字對象有整數(shù)和浮點(diǎn)數(shù),支持各種數(shù)學(xué)操作,比如+, -,*, /等。 沒有這些操作符,程序中只能使用函數(shù)調(diào)用的方式進(jìn)行數(shù)學(xué)運(yùn)算,比如add(2, 3), sub(5, 2)。
程序中操作符的作用與普通數(shù)學(xué)操作的用法是一致的,使用中更加簡便直觀。Python中,這些操作符實(shí)現(xiàn)是通過定義一些object的特殊方法實(shí)現(xiàn)的,比如object.__add__()和object.__sub__()。如果用戶在自己定義類時(shí)實(shí)現(xiàn)上述特殊方法,可以使自定義類的對象支持相應(yīng)的數(shù)學(xué)操作,從而模擬數(shù)字對象的行為。這其實(shí)是達(dá)到了操作符重載的效果。
這里通過實(shí)現(xiàn)一個(gè)具有支持加法運(yùn)算的中文數(shù)字類說明如何在Python中實(shí)現(xiàn)一個(gè)支持常見的數(shù)學(xué)操作。ChineseNumber類的基本定義如下。
class ChineseNumber: def __init__(self, n): self.num = n self.alphabet = [u'零', u'一', u'二', u'三', u'四', u'五', u'六', u'七', u'八', u'九', u'十'] def __str__(self): sign = '負(fù)' if self.num < 0 else '' return sign + ''.join([self.alphabet[int(s)] for s in str(abs(self.num))]) def __repr__(self): return self.__str__()
目前,實(shí)現(xiàn)的效果是這樣的:
>>> a = ChineseNumber(2) >>> a #調(diào)用a.__repr__() 二 >>> print(a) #調(diào)用a.__str__() 二
一般數(shù)學(xué)操作符
定義類時(shí),實(shí)現(xiàn)__add__()方法,可以給這個(gè)類增加+操作符。給ChineseNumber增加如下方法:
def __add__(self, other): if type(other) is ChineseNumber: return ChineseNumber(self.num + other.num) elif type(other) is int: return ChineseNumber(self.num + other) else: return NotImplemented
這時(shí)ChineseNumber的對象就可以使用+了。
>>> a, b = ChineseNumber(2), ChineseNumber(10) >>> a + b 十二 >>> a + 5 七 >>> a + 3.7 TypeError: unsupported operand type(s) for +: 'ChineseNumber' and 'float'
對于+,a + b相當(dāng)于調(diào)用a.__add__(b). 類似地,可以定義其他數(shù)學(xué)操作符,見下表。
object.__add__(self, other): + object.__sub__(self, other): - object.__mul__(self, other): * object.__matmul__(self, other): @ object.__truediv__(self, other): / object.__floordiv__(self, other): // object.__mod__(self, other): % object.__divmod__(self, other): divmod, divmod(a, b) = (a/b, a%b) object.__pow__(self, other[,modulo]): **, pow() object.__lshift__(self, other): << object.__rshift__(self, other): >> object.__and__(self, other): & object.__xor__(self, other): ^ object.__or__(self, other): |
操作數(shù)反轉(zhuǎn)的數(shù)學(xué)操作符 (Reflected/Swapped Operand)
>>> 2 + a TypeError: unsupported operand type(s) for +: 'int' and 'ChineseNumber'
2是整數(shù)類型,它的__add__()方法不支持ChineseNumber類的對象,所以出現(xiàn)了上述錯(cuò)誤。定義操作數(shù)反轉(zhuǎn)的數(shù)學(xué)操作符可以解決這個(gè)問題。給ChineseNumber類添加__radd__()方法,實(shí)現(xiàn)操作數(shù)反轉(zhuǎn)的+運(yùn)算。
def __radd__(self, other): return self.__add__(other)
對于a + b,如果a沒有定義__add__()方法,Python嘗試調(diào)用b的__radd__()方法。此時(shí),a + b相當(dāng)于調(diào)用b.__radd__(a)。
>>> a = ChineseNumber(2) >>> 2 + a 四
類似地,可以定義其他操作數(shù)反轉(zhuǎn)的數(shù)學(xué)操作符,見下表。
object.__radd__(self, other): + object.__rsub__(self, other): - object.__rmul__(self, other): * object.__rmatmul__(self, other): @ object.__rtruediv__(self, other): / object.__rfloordiv__(self, other): // object.__rmod__(self, other): % object.__rdivmod__(self, other): divmod, divmod(a, b) = (b/a, b%a) object.__rpow__(self, other[,modulo]): **, pow() object.__rlshift__(self, other): << object.__rrshift__(self, other): >> object.__rand__(self, other): & object.__rxor__(self, other): ^ object.__ror__(self, other): |
運(yùn)算賦值操作符
運(yùn)算賦值操作符使用單個(gè)操作符完成運(yùn)算和賦值操作,比如a += b相當(dāng)于調(diào)用a = a + b。為ChineseNumber增加__iadd__()方法,可以實(shí)現(xiàn)+=操作符。
def __iadd__(self, other): if type(other) is ChineseNumber: self.num += other.num return self elif type(other) is int: self.num += other return self else: return NotImplemented
此時(shí),
>>> a, b = ChineseNumber(2), ChineseNumber(10) >>> a += b >>> a 十二 >>> a + 7 >>> a 十九
類似地,可以定義其他運(yùn)算賦值操作符,見下表。
object.__iadd__(self, other): += object.__isub__(self, other): -= object.__imul__(self, other): *= object.__imatmul__(self, other): @= object.__itruediv__(self, other): /= object.__ifloordiv__(self, other): //= object.__imod__(self, other): %= object.__ipow__(self, other[,modulo]): **= object.__ilshift__(self, other): <<= object.__irshift__(self, other): >>= object.__iand__(self, other): &= object.__ixor__(self, other): ^= object.__ior__(self, other): |=
一元數(shù)學(xué)操作符
一元數(shù)學(xué)操作符是只有一個(gè)操作數(shù)的運(yùn)算,比如取負(fù)數(shù)的操作符-。-對應(yīng)的特殊函數(shù)是__neg__()。為ChineseNumber添加__neg__()方法,
def __neg__(self): return ChineseNumber(-self.num)
此時(shí),ChineseNumber對象就支持-操作了。
>>> a = ChineseNumber(5) >>> -a 負(fù)五
其他一元運(yùn)算符見下表。
object.__neg__(self): - object.__pos__(self): + object.__abs__(self): abs() object.__invert__(self): ~ object.__complex__(self): complex() object.__int__(self): int() object.__float__(self): float() object.__round__(self): round() object.__index__(self): operator.index()
相關(guān)文章
python使用裝飾器和線程限制函數(shù)執(zhí)行時(shí)間的方法
這篇文章主要介紹了python使用裝飾器和線程限制函數(shù)執(zhí)行時(shí)間的方法,主要涉及timelimited函數(shù)的使用技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-04-04Pandas聚合運(yùn)算和分組運(yùn)算的實(shí)現(xiàn)示例
這篇文章主要介紹了Pandas聚合運(yùn)算和分組運(yùn)算的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10Python pandas讀取CSV文件的注意事項(xiàng)(適合新手)
這篇文章主要給大家介紹了關(guān)于Python pandas讀取CSV文件的注意事項(xiàng),非常適合新手,csv是我接觸的比較早的一種文件,比較好的是這種文件既能夠以電子表格的形式查看又能夠以文本的形式查看,需要的朋友可以參考下2021-06-06解決Python3 控制臺輸出InsecureRequestWarning問題
這篇文章主要介紹了解決Python3 控制臺輸出InsecureRequestWarning的問題 ,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-07-07python datetime時(shí)間格式的相互轉(zhuǎn)換問題
這篇文章主要介紹了python datetime時(shí)間格式的相互轉(zhuǎn)換問題,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06YOLOv5車牌識別實(shí)戰(zhàn)教程(七)實(shí)時(shí)監(jiān)控與分析
這篇文章主要介紹了YOLOv5車牌識別實(shí)戰(zhàn)教程(七)實(shí)時(shí)監(jiān)控與分析,在這個(gè)教程中,我們將一步步教你如何使用YOLOv5進(jìn)行車牌識別,幫助你快速掌握YOLOv5車牌識別技能,需要的朋友可以參考下2023-04-04