python中的运算符重载
其实我一直不明白为什么有人一定要用python一个脚本语言去实现c++或是java的功能……
不过既然人家有这样的用法,那就写写吧。
举个栗子:
实现加法的重载。
class Fruit:
def __init__(self,price=0):
self.price=price
def __add__(self,other):
return self.price+other.price
def __gt__(self,other):
if self.price>other.price:
flag=True
else:
flag=False
return flag
class Apple(Fruit):
pass
class Banana(Fruit):
pass
if __name__=="__main__":
apple=Apple(3)
print"the price of apple:",apple.price
banana=Banana(4)
print"the price of banana:",banana.price
print apple>banana
total=apple+banana
print "total is:",total
列为看官可能会疑惑,说好的重载运算符,符呢?
在python中,python把运算法和内置方法联系起来,没个运算符都对应着一个函数。
其中,_ _add __()就是表示运算符“+”
而_ _gt __()表示运算符“>”
(原谅我渣渣的排版。)
结果如下:
the price of apple: 3
the price of banana: 4
False
total is: 7
另外python还可以重载<<,个人觉得没意思,作为一个还没有实战经验的大学狗来说,不玩儿了。