Python中的數(shù)學運算操作符使用進階
Python中對象的行為是由它的類型 (Type) 決定的。所謂類型就是支持某些特定的操作。數(shù)字對象在任何編程語言中都是基礎元素,支持加、減、乘、除等數(shù)學操作。
Python的數(shù)字對象有整數(shù)和浮點數(shù),支持各種數(shù)學操作,比如+, -,*, /等。 沒有這些操作符,程序中只能使用函數(shù)調用的方式進行數(shù)學運算,比如add(2, 3), sub(5, 2)。
程序中操作符的作用與普通數(shù)學操作的用法是一致的,使用中更加簡便直觀。Python中,這些操作符實現(xiàn)是通過定義一些object的特殊方法實現(xiàn)的,比如object.__add__()和object.__sub__()。如果用戶在自己定義類時實現(xiàn)上述特殊方法,可以使自定義類的對象支持相應的數(shù)學操作,從而模擬數(shù)字對象的行為。這其實是達到了操作符重載的效果。
這里通過實現(xiàn)一個具有支持加法運算的中文數(shù)字類說明如何在Python中實現(xiàn)一個支持常見的數(shù)學操作。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 = '負' 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__()
目前,實現(xiàn)的效果是這樣的:
>>> a = ChineseNumber(2) >>> a #調用a.__repr__() 二 >>> print(a) #調用a.__str__() 二
一般數(shù)學操作符
定義類時,實現(xiàn)__add__()方法,可以給這個類增加+操作符。給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
這時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相當于調用a.__add__(b). 類似地,可以定義其他數(shù)學操作符,見下表。
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ù)反轉的數(shù)學操作符 (Reflected/Swapped Operand)
>>> 2 + a TypeError: unsupported operand type(s) for +: 'int' and 'ChineseNumber'
2是整數(shù)類型,它的__add__()方法不支持ChineseNumber類的對象,所以出現(xiàn)了上述錯誤。定義操作數(shù)反轉的數(shù)學操作符可以解決這個問題。給ChineseNumber類添加__radd__()方法,實現(xiàn)操作數(shù)反轉的+運算。
def __radd__(self, other): return self.__add__(other)
對于a + b,如果a沒有定義__add__()方法,Python嘗試調用b的__radd__()方法。此時,a + b相當于調用b.__radd__(a)。
>>> a = ChineseNumber(2) >>> 2 + a 四
類似地,可以定義其他操作數(shù)反轉的數(shù)學操作符,見下表。
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): |
運算賦值操作符
運算賦值操作符使用單個操作符完成運算和賦值操作,比如a += b相當于調用a = a + b。為ChineseNumber增加__iadd__()方法,可以實現(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
此時,
>>> a, b = ChineseNumber(2), ChineseNumber(10) >>> a += b >>> a 十二 >>> a + 7 >>> a 十九
類似地,可以定義其他運算賦值操作符,見下表。
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ù)學操作符
一元數(shù)學操作符是只有一個操作數(shù)的運算,比如取負數(shù)的操作符-。-對應的特殊函數(shù)是__neg__()。為ChineseNumber添加__neg__()方法,
def __neg__(self): return ChineseNumber(-self.num)
此時,ChineseNumber對象就支持-操作了。
>>> a = ChineseNumber(5) >>> -a 負五
其他一元運算符見下表。
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()
相關文章
python使用裝飾器和線程限制函數(shù)執(zhí)行時間的方法
這篇文章主要介紹了python使用裝飾器和線程限制函數(shù)執(zhí)行時間的方法,主要涉及timelimited函數(shù)的使用技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04Python pandas讀取CSV文件的注意事項(適合新手)
這篇文章主要給大家介紹了關于Python pandas讀取CSV文件的注意事項,非常適合新手,csv是我接觸的比較早的一種文件,比較好的是這種文件既能夠以電子表格的形式查看又能夠以文本的形式查看,需要的朋友可以參考下2021-06-06解決Python3 控制臺輸出InsecureRequestWarning問題
這篇文章主要介紹了解決Python3 控制臺輸出InsecureRequestWarning的問題 ,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07YOLOv5車牌識別實戰(zhàn)教程(七)實時監(jiān)控與分析
這篇文章主要介紹了YOLOv5車牌識別實戰(zhàn)教程(七)實時監(jiān)控與分析,在這個教程中,我們將一步步教你如何使用YOLOv5進行車牌識別,幫助你快速掌握YOLOv5車牌識別技能,需要的朋友可以參考下2023-04-04