gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:52:42 26 4
gpt4 key购买 nike

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

def multiply(a, b):
return a * b

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

In [5]: multiply(2,3)
Out[5]: 6

但是(令人惊讶地)知道 Python 是一种强类型语言,这也同样有效:

In [6]: multiply('2', 3)
Out[6]: '222'

或者这个

In [7]: multiply(3, '2')
Out[7]: '222'

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

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

最佳答案

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

  • * = 重复 '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

如您所见,其中包含运算符 __add____mul__用于加法和乘法。

关于python - 为什么Python允许str与int相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32431677/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com