python __add__()方法

__add__()方法

python 中的__add__()方法,可以用于向列表、元组、字符串中添加参数指定列表或元组或字符串中的元素或字符,注意不是数值。如果调用对象为int或float,返回值为调用对象和参数的相加和。


语法

Obj.__add__( self, value, / )

python源码中对__add__()方法的介绍:

Return self+value.

参数

参数描述
value值为python中的列表、元组或字符串或int或float。

返回值

正如python中源码的介绍return self+value,即返回值为将参数中的元素添加到调用对象中,或返回调用对象和参数的相加和。


__add__()方法实例代码

>>> [].__add__([1])
[1]
>>> [1].__add__([2]) #调用对象为列表
[1, 2]
>>> ''.__add__('abc') #调用对象为字符串
'abc'
>>> (1,).__add__((2,3)) #调用对象为元组
(1, 2, 3)
>>> num = 1
>>> num.__add__(2) #调用对象为int
3
>>> [].__add__(1) #传递的参数为int,非列表,与调用对象类型不对应,python抛出TypeError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>> [].__add__((1,2)) #传递的参数为tuple
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list
>>> [].__add__() #没有传递参数
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected 1 arguments, got 0

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.