python中的运算符重载

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还可以重载<<,个人觉得没意思,作为一个还没有实战经验的大学狗来说,不玩儿了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值