Skip to main content
 首页 » 编程设计

python之Python 在添加两个变量时选择的默认值是多少

2025年05月04日28zhenyulu

假设我们有以下上下文:

x = 3   
y = 4   
z = x + y 

z 是 int 还是 float 等?我很清楚 float 确实以 .something 结尾,但是我不清楚 Python 是否会偏爱浮点类型而不是整数类型,因为在这种情况下用户是否要去是不可预测的是否将此变量更改为另一种类型。

请您参考如下方法:

当混合 类型时,您总是会得到“更宽”的类型,其中复数比 float 宽,而 float 又比整数宽。当两个值是相同类型时(因此不是混合类型),您将只获得一种类型作为结果。

来自Numeric Types documentation :

Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where plain integer is narrower than long integer is narrower than floating point is narrower than complex. Comparisons between numbers of mixed type use the same rule.

因此,当您对不同类型的数字求和时,Python 会将较窄的类型加宽为与较宽的类型相同。对于整数和 float 的运算,您将得到一个 float ,因为 float 更宽。

但是,如果两个操作数的类型相同,则没有必要更改类型。在这种情况下更改类型将是非常令人惊讶的。