python中的运算符重载

来源:互联网 发布:java i18n 国际化 编辑:程序博客网 时间:2024/06/05 02:04

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 flagclass Apple(Fruit):    passclass Banana(Fruit):    passif __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: 3the price of banana: 4Falsetotal is: 7

另外python还可以重载<<,个人觉得没意思,作为一个还没有实战经验的大学狗来说,不玩儿了。

0 0
原创粉丝点击