为什么Python允许str与int相乘?

who*_*ami 1 python types

假设我们定义一个函数如下:

def multiply(a, b):
    return a * b
Run Code Online (Sandbox Code Playgroud)

通过传递数字来调用它显然是有效的:

In [5]: multiply(2,3)
Out[5]: 6
Run Code Online (Sandbox Code Playgroud)

但这(令人惊讶地)知道Python是一种强类型的语言,同样也可以工作:

In [6]: multiply('2', 3)
Out[6]: '222'
Run Code Online (Sandbox Code Playgroud)

或这个

In [7]: multiply(3, '2')
Out[7]: '222'
Run Code Online (Sandbox Code Playgroud)

隐式类型转换让我非常害怕。str类型设计决策背后的原理是什么?另一方面,在F#中,它是不允许的:

- '3' * 2;;
  '3' * 2;;
  ------^
/Users/Pac/stdin(14,7): error FS0001: The type 'int' does not match the type 'char'
Run Code Online (Sandbox Code Playgroud)

Ste*_*nes 5

没有进行类型转换,但是字符串类型具有许多操作,这些操作提供了有用的快捷方式,当您考虑它时,它们是很合逻辑的:

  • 乘法*=重复所以'abcd ' * 4 -> 'abcd abcd abcd abcd '
  • 添加+=串联'abcd' + 'efg' -> 'abcdefg' 但是 'abcd' + 3 -> TypeError: cannot concatenate 'str' and 'int' objects

窍门,找出哪些操作是可用于任何给定类型的,比阅读手册等, dir(x)help(x)其中x是一个实例的类型,所以:

dir('a')
__add__, __class__, __contains__, __delattr__, __doc__, __eq__, __format__, 
__ge__, __getattribute__, __getitem__, __getnewargs__, __getslice__, __gt__,
__hash__, __init__, __le__, __len__, __lt__, __mod__, __mul__, __ne__, __new__,
__reduce__, __reduce_ex__, __repr__, __rmod__, __rmul__, __setattr__,
__sizeof__, __str__, __subclasshook__, _formatter_field_name_split, _formatter_parser,
capitalize, center, count, decode, encode, endswith, expandtabs, find, format, index,
isalnum, isalpha, isdigit, islower, isspace, istitle, isupper, join, ljust,
lower, lstrip, partition, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip,
split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill
Run Code Online (Sandbox Code Playgroud)

如您所见,其中包含运算符__add__以及__mul__加法和乘法。