## Python的return self和return一个新的对象区别

### 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


### 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
>>> r2 = r1.plus(Rational0(7,15))
>>> r2.print()
80/75
>>> r2
>>> 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


posted on 2018-09-08 15:31  星辰之衍  阅读(250)  评论(0编辑  收藏