隨手扎
覆寫Python操作子(Override Operator)
上一篇寫到Python裡的方法和函數。接著來看看 操作方法 。
Python的操作子
a < b
a <= b
a == b
a != b
a >= b
a > b
a + b
a - b
a * b
a ** b
a / b
a // b
a and b
a or b
上面都是寫Python常見的形式。其實這些操作方法和C++一樣,可以覆寫(Override Operator)。要覆寫,只要在定義類別時,添加對應方法就好。
為String擴展+的方法
Python是偏強型別語言,雖然字串可以乘上數字(ex:"-"*10
),但是不能加上數字。就來簡單的擴展作為範例看看吧!
count = 10
"-"*10
# "Count: " + count # will rise exception
"Count: " + str(count) # allow string + string
class myString(str):
def __add__(self, other):
if other == None:
return myString(str(self) + "None")
elif type(other) == str:
return myString(str(self) + other)
elif type(other) == int or type(other) == float:
return myString(str(self) + str(other))
else:
return myString(str(self) + str(other))
myString("Count: ") + count # success. => 'Count: 10'
myString("Count: ") + count + " and " + count # => 'Count: 10 and 10'
myString("Count: ") + None # => 'Count: None'
實例覆寫方法(不可)
上一篇比較了方法和函數。雖然可以直接為物件實例添加__add__(a,b)
,但是使用a+b
的會呼要類別裡定義的方法。這有點像是:
def callAdd(obj, other):
type(obj).__add__(obj, other)
所以:
count = 10
instance = myString("Count: ")
instance.__add__ = lambda other: "Hello, World"
instance.__add__(10) # => "Hello World"
instance + 10 # => "Count: 10"
你仍然可以顯示呼叫instance.__add__
,不過當使用instance + 10
時,則不會執行instance.__add__
的定義內容。
Python常見運算子
更多請參考:operator
操作子 | 方法名稱 |
---|---|
比較運算 | |
a < b | __lt__(a,b) |
a <= b | __le__(a,b) |
a == b | __eq__(a,b) |
a != b | __ne__(a,b) |
a >= b | __ge__(a,b) |
a > b | __gt__(a,b) |
邏輯運算 | |
__bool__() | |
(對象實例沒有__not__() 方法) | |
a and b | __and__(a,b) |
數學運算 | |
a + b | __add__(a,b) |
~obj | __invert__(obj) |
a«b | __lshift__(a,b) |
a»b | __rshift__(a,b) |
a*b | __mul__(a,b) |
-a | __neg__(obj) |
a**b | __pow__(a,b) |
a - b | __sub__(a,b) |
a ^ b | __xor__(a,b) |
a // b | __floordiv__(a, b) |
序列運算 | __concat__(a,b) |
a + b | __contains__(a,b) |
原地運算 | |
a += b | __iadd__(a,b) |
a *= b | __imul__(a,b) |
a -= b | __isub__(a,b) |
a //= b | __ifloordiv__(a, b) |
