首页 > 其他 > 详细

运算符重载

时间:2020-07-13 01:01:50      阅读:71      评论:0      收藏:0      [点我收藏+]
# :运算符重载

class person:
def __init__(self,num):
self.num = num
def __add__(self, other): #:调用了__add__运算符 含义为进行"+"法运算
return person(self.num + other.num) #:self == "第一个实例",other == "后面的实例"
#:这里返回的时person实例 并且实例中有一个num 属性

if __name__ == ‘__main__‘:
p1 = person(10) #:p1 传入到实例中 == slef
p2 = person(20) #:p2 传入到实例中 == other
p3 = p1 + p2 #:p3 进行实例和实例之间的运算
print(p3.num) #:最后调用的时候直接拿出person里面的属性即可


#:使用__str__拿出结果
class person:
def __init__(self,num):
self.num = num
def __add__(self, other):
return person(self.num + other.num)
def __str__(self): #:可以直接使用上述的__str__
return "num = "+str(self.num)

if __name__ == ‘__main__‘:
p1 = person(10)
p2 = person(20)
print(p1 + p2)

‘‘‘
思路:
1.首先__add__来进行+法运算
这时p1传入了10 p2传入了20 分别咱__add__中为slef == p1 other == p2
2.然后当代码进行到调用print函数的时候 会调用__str__
__str__特点:
当有print 函数的时候会被自动调用
之后__add__返回了person实例所以self == person(num)
3.__str__这时返回self.num 那么就相当于 person.num 这个时候在进行运算的值就被拿出来了
‘‘‘

#:使用__repr__拿出结果
class person:
def __init__(self,num):
self.num = num
def __add__(self, other):
return person(self.num + other.num)
def __repr__(self): #:使用repr也是同理
return "num = "+str(self.num)

if __name__ == ‘__main__‘:
p1 = person(10)
p2 = person(20)
p3 = p1 + p2
print(p3)

运算符重载

原文:https://www.cnblogs.com/yandh/p/13290850.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!