Python__add__()函数是Python中返回一个新对象(第三个)的神奇方法之一,即添加其他两个对象对象。它实现了加法运算符 “+”在Python.
Python __add__() 语法
Syntax: obj1.__add__(self, obj2)
- obj1: First object to add in the second object.
- obj2: Second object to add in the first object.
Returns: Returns a new object representing the summation of the other two objects.
Python __add__() 魔术方法示例
Python __add__() 方法添加两个对象并返回一个新的 object 作为 Python. 中的结果对象 下面的示例返回一个新对象,
Python3
class GFG:
def __init__(self, val):
self.val = val
def __add__(self, val2):
return GFG(self.val + val2.val)
obj1 = GFG("Geeks")
obj2 = GFG("ForGeeks")
obj3 = obj1 + obj2
print(obj3.val)
输出:
GeeksForGeeks
注意: 如果我们没有定义__add__()方法,Python会提出 TypeError.
Python3
class GFG:
def __init__(self, val):
self.val = val
obj1 = GFG("Geeks")
obj2 = GFG("ForGeeks")
obj3 = obj1 + obj2
print(obj3.val)
输出:
Traceback (most recent call last): File "/home/d8b3b04f2954b8c46b64bc7dd37f6aa4.py", line 11, in <module> obj3 = obj1 + obj2 TypeError: unsupported operand type(s) for +: 'GFG' and 'GFG'
相关用法
- Python __import__()用法及代码示例
- Python __getslice__用法及代码示例
- Python __rmul__用法及代码示例
- Python __getitem__()用法及代码示例
- Python __call__用法及代码示例
- Python __exit__用法及代码示例
- Python __new__用法及代码示例
- Python __init__用法及代码示例
- Python __file__用法及代码示例
- Python __name__用法及代码示例
- Python __len__()用法及代码示例
- Python __repr__()用法及代码示例
- Python String format()用法及代码示例
- Python abs()用法及代码示例
- Python any()用法及代码示例
- Python all()用法及代码示例
- Python ascii()用法及代码示例
- Python bin()用法及代码示例
- Python bool()用法及代码示例
- Python bytearray()用法及代码示例
- Python callable()用法及代码示例
- Python bytes()用法及代码示例
- Python chr()用法及代码示例
- Python compile()用法及代码示例
- Python classmethod()用法及代码示例
注:本文由纯净天空筛选整理自shlokdi35dq大神的英文原创作品 Python __add__() magic method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。