目的:设计一个有理数相加。如3/5 + 7/15 = 80/75

return self

输入:

class Rational0:
def __init__(self, num, den=1):
self.num = num
self.den = den def plus(self, another):
den = self.den * another.den
num = (self.num * another.den + self.den * another.num)
return self def print(self):
print(str(self.num) + "/" + str(self.den))

输出:

>>> r1 = Rational0(3, 5)
>>> r1.print()
3/5
>>> r1
<__main__.Rational0 object at 0x000001D1D91A5F60>
>>> r2 = r1.plus(Rational0(7,15)) # 新对象r2
>>> r2
<__main__.Rational0 object at 0x000001D1D91A5F60> # 地址相同
>>> r1.plus(Rational0(7,15)).print() #或者r2.print()
3/5
>>> r2.num
3
>>> r2.den
5

从地址中可以看出Rational0(3, 5)r1.plus(Rational0(7,15))返回的对象是同一个r1地址,原因在于return self

return self做出修改

class Rational0:
def __init__(self, num, den=1):
self.num = num
self.den = den def plus(self, another):
den = self.den * another.den
num = (self.num * another.den + self.den * another.num)
self.den = den
self.num = num
return self
#return Rational0(num, den) def print(self):
print(str(self.num) + "/" + str(self.den)) r1 = Rational0(3, 5)
r2 = r1.plus(Rational0(7,15))
r2.print()

输出:

>>> r1 = Rational0(3, 5)
>>> r1.print()
3/5
>>> r1
<__main__.Rational0 object at 0x00000239CADF5E80>
>>> r2 = r1.plus(Rational0(7,15))
>>> r2.print()
80/75
>>> r2
<__main__.Rational0 object at 0x00000239CADF5E80>
>>> r2.num
80
>>> r2.den
75

分析:





return新的对象

输入:

class Rational0:
def __init__(self, num, den=1):
self.num = num
self.den = den def plus(self, another):
den = self.den * another.den
num = (self.num * another.den + self.den * another.num)
return Rational0(num, den) def print(self):
print(str(self.num) + "/" + str(self.den))

输出:

>>> r1 = Rational0(3, 5)
>>> r1.print()
3/5
>>> r1
<__main__.Rational0 object at 0x000001F857C35DD8>
>>> r2 = r1.plus(Rational0(7,15)) # 新对象r2
<__main__.Rational0 object at 0x000001F857C48940> #地址不同
>>>r2.print()
80/75
>>> r2.num
80
>>> r2.den
75

从地址中可以看出Rational0(3, 5)r1.plus(Rational0(7,15))返回的对象不是同一个,原因在于return Rational0(num, den)

最新文章

  1. Jesse Livermore的21句投机至理名言
  2. 从零开始攻略PHP(7)——面向对象(上)
  3. PHPCMS 实现上一篇下一篇的几种方法
  4. Linux搭建SVN服务器(centos)
  5. Science:给青年科研工作者的忠告
  6. Jquery扩展-手把手带你体验
  7. [RxJS] Stream Processing With RxJS vs Array Higher-Order Functions
  8. Lintcode--001(比较字符串)
  9. form表单提交图片禁止跳转
  10. Getting the pixel coordinates of text or ticks in matplotlib
  11. Flask 学习 五 电子邮件
  12. 基于MySQL的Activiti6引擎创建
  13. 免费赠送原创的opengl电子书教程和案例源码
  14. mayavi与X11的一些坑总结
  15. WordPress版微信小程序2.2.8版发布
  16. 免费SMTP邮件服务:Mandrill,Sendgrid,Mailjet,Postmarkapp,MailChimp
  17. .5-浅析express源码之Router模块(1)-默认中间件
  18. 使用mysql innodb 使用5.7的json类型遇到的坑和解决办法
  19. Elasticsearch学习之深入聚合分析一---基本概念
  20. 【VUE】vue项目开发中,setTimeout等定时器的管理。

热门文章

  1. Gmail 邮件配置备忘
  2. Machine Learning第十周笔记:大规模机器学习
  3. Java Modifier
  4. 【BZOJ4898】[Apio2017]商旅 分数规划+SPFA
  5. WCF基础之事务
  6. CAS 源码编译
  7. asp.net mvc4连接mysql
  8. 以层的观点思考各个nginx的log位置
  9. 【转】mysql利用init-connect增加访问审计功能
  10. javascript实例:两种方式实现tab栏选项卡