python __mul__()方法
__mul__()语法
python内置方法__mul__()的语法如下:
__mul__(self, value, /)
__mul__()方法会根据调用对象的不同,执行不同的乘法运算,python源码中的介绍为:
Return self*value.
提示:python的字典dict和结合set等不能有重复键或元素的数据结构,没有__mul__()方法。
参数
参数 | 描述 |
---|---|
value | 如果调用对象不是float,那么一般情况下,参数value为python整型int数值 |
返回值
根据调用__mul__()方法的对象返回相应类型的值,比如1*2,返回2;1.1*2,返回2.2;[1]*2,则返回[1,1]等等,具体见下方实例。
>>> (1).__mul__(3)
3
>>> (1.1).__mul__(5)
5.5
>>> 'a'.__mul__(6)
'aaaaaa'
>>> (2,).__mul__(3)
(2, 2, 2)
>>> [3,2].__mul__(3)
[3, 2, 3, 2, 3, 2]
>>> {1,2}.__mul__(2) #调用对象为集合set
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'set' object has no attribute '__mul__'
>>> {'a':1}.__mul__(5) #调用对象为字典dict
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute '__mul__'
>>> 'b'.__mul__(1.6) #调用对象为字符串,参数为float
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
>>> (1).__mul__(1.8) #调用对象为int,参数为float
NotImplemented
>>> (1.2).__mul__(2.1) #调用对象为float,参数为float
2.52