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
- python中的运算符重载
- python中的运算符重载
- Python运算符重载
- Python运算符重载
- Python运算符重载
- Python运算符重载
- Python运算符重载
- python 重载运算符
- Python运算符重载
- python重载运算符
- python运算符重载
- Python 运算符重载
- Python运算符重载
- Python 运算符重载
- Python运算符重载
- Python-运算符重载
- Python 运算符重载
- [Python]重载运算符
- yii2下使用自带类发送邮件
- Spring Boot实现热部署(hot swapping)
- 深入浅出看流媒体前世今生,分分钟二逼变牛逼
- Struts学习笔记: 实现文件上传下载
- enum 字典码用法
- python中的运算符重载
- CentOS 7 下STF的安装
- 用PHP实现简单登录v2.0
- js替换
- 有关内存泄露
- iOS 10推送 - UserNotifications
- jenkins+sonar+maven+svn+tomcat集成
- Android缓存机制学习笔记
- linux 安装 nodejs