<>add

正确代码
class Data: def __init__(self,number): self.number = number
#注意other和self.number顺序不能乱 def __add__(self,other): return other + self.number if
__name__== '__main__': number1 = Data(30) number2 = Data(20) print(number1 +
number2) [root@master python]# python3 test.py 50
错误代码
class Data: def __init__(self,number): self.number = number def __add__(self,
other): return self.number + other if __name__ == '__main__': number1 = Data(30)
number2= Data(20) print(number1 + number2) [root@master python]# python3
test.py Traceback (most recent call last): File "test.py", line 43, in <module>
print(number1 + number2) File "test.py", line 32, in __add__ return self.number
+ other TypeError: unsupported operand type(s) for +: 'int' and 'Data'
<>iter
cat iter.py #!/usr/bin/env python #coding: utf-8 class Data: def __init__(self,
role_items): self.role_items = role_items def __iter__(self): for i in self.
role_items: yield i def __radd__(self,other): return other+list(self) def test(
self): return Data([role_items]) role=[1,2,3] data=Data(role) print(data) for i
in data: print(i) python3 iter.py <__main__.Data object at 0x7f2f09f084e0> 1 2 3
<>radd
cat iter.py #!/usr/bin/env python #coding: utf-8 class Data: def __init__(self,
role_items): self.role_items = role_items def __iter__(self): for i in self.
role_items: yield i def __radd__(self,other): return other+list(self) def test(
self): return Data([role_items]) role=[1,2,3] data=Data(role) #print(data) #for
i in data: # print(i) list1=[4,5,6] print(list1+data) python3 iter.py [4, 5, 6,
1, 2, 3]

技术
今日推荐
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:766591547
关注微信