Python比其他脚本语言更强类型.例如,在Perl中:
perl -E '$c=5; $d="6"; say $c+$d' #prints 11
Run Code Online (Sandbox Code Playgroud)
但是在Python中:
>>> c="6"
>>> d=5
>>> print c+d
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
Run Code Online (Sandbox Code Playgroud)
Perl将检查字符串并转换为数字,并且+ - / * **运算符按预期使用数字.PHP类似.
Python用于+连接字符串,因此尝试的操作c+d失败,因为c是一个字符串,d是一个int.Python 比Perl 具有更强的数字类型感.好的 - 我可以解决这个问题.
但考虑一下:
>>> from sys import maxint
>>> type(maxint)
<type 'int'>
>>> print maxint
9223372036854775807
>>> type(maxint+2)
<type 'long'>
>>> print maxint+2
9223372036854775809
>>> type((maxint+2)+maxint)
<type 'long'>
>>> …Run Code Online (Sandbox Code Playgroud) 是否有可能以某种方式覆盖或重载 python 中整数/数字的标准实现,使其像 32 位整数一样工作。
a: int
a = 4076863488
>>> -218103808
Run Code Online (Sandbox Code Playgroud)
或者是否有可能以某种方式定义一个不能改变类型的变量?这样做是这样的:x: int?我想这样做是因为ctypes.c_int32(n)在每个位操作和赋值上都写很烦人。特别是因为 Python 不使用 32 位按位操作数。
我知道我基本上是在尝试改变语言的性质。所以也许我在问如果你必须在 python 中做 32 位的东西你会怎么做。