python 運算符重載__add__


print(1 + 2)
print("1" + "2")
#不同的類型用加法會有不同的解釋

class Person(object):
def __init__(self, num):
self.num = num
#運算符重載
def __add__(self, other):
return Person(self.num + other.num)
def __str__(self):
return "num = " + str(self.num)
per1 = Person(1)
per2 = Person(2)
print(per1 + per2)#per1 + per2 ==== per1.__add__(per2)
#print(per1.__add__(per2))
print(per1)
print(per2)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM