python 運算子過載

2021-09-11 08:22:58 字數 1758 閱讀 4587

python的運算子過載還是很方便的,記錄以下**以便回顧

class fees:

def __init__(self, data):

"""將字串「num1-num2」構建成自己的資料結構

:param data:

"""self.data = str(data)

num_list = re.findall('[\d\.]+', self.data)

self.num1, self.num2 = float(num_list[0]), float(num_list[1]) if len(num_list) > 1 else none

def __str__(self):

"""列印出來的字串

:return: 'num1~num2'的字串,兩個數字保留兩位小數

"""if self.num2 and self.num2 > self.num1:

return '~'.format(self.num1, self.num2)

else:

return ''.format(self.num1)

def __add__(self, other):

"""過載加法運算

:param other: 另外乙個fees型別值:fees(onum1, onum2),onum2可能為空

:return:

"""if other.num2 is none:

return fees(str(self.num1 + other.num1) + '-' + str(self.num2 + other.num1))

else:

return fees(str(self.num1 + other.num1) + '-' + str(self.num2 + other.num2))

def __mul__(self, other):

"""過載乘法運算

:param other: 另外乙個fees型別值:fees(onum1, onum2),onum2可能為空

:return:

"""if other.num2 is none:

return fees(str(self.num1 * other.num1) + '-' + str(self.num2 * other.num1))

else:

return fees(str(self.num1 * other.num1) + '-' + str(self.num2 * other.num2))

def __getitem__(self, item):

"""過載索引

:param item:

:return:

"""if int(item) == 0:

return float(self.num1)

elif int(item) == 1:

return float(self.num2)

def __setitem__(self, key, value):

"""過載索引賦值

:param key:

:param value:

:return:

"""if int(key) == 0:

self.num1 = value

elif int(key) == 1:

self.num2 = value

self.data = fees(str(self.num1) + '-' + str(self.num2))

Python 運算子過載

在 python 中is 是兩個運算子,對物件進行比較,分別對id,type value 進行比較。is 比較id type value三維 而 僅 比較value。實驗發現其實is,僅僅是比較一些簡單的基礎變數。class test object def init self self.value ...

Python運算子過載

print 呼叫父類建構函式 def parentmethod self print 呼叫父類方法 def setattr self,attr self.parentattr attr def getattr self print 父類屬性 self.parentattr def del self ...

python 運算子過載

運算子過載就是讓用類寫成的物件,可截獲並響應用在內建型別上的運算 加法,切片,列印和點號運算等 1.以雙下劃線命名的方法 x 的特殊鉤子,python運算子過載的實現是提供特殊命名的方法來攔截運算,python替每種運算和特殊命名的方法之間,定義了固定不變的對映關係 2.當例項出現在內建運算時,這類...