You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么我的Python代码无论传入什么类型都始终输出“small int”?

问题原因分析
  • 核心错误是误用了is运算符做类型判断:Python中is的作用是校验两个对象的内存地址是否完全相同,而非判断类型匹配。代码中if probe is str的逻辑是判断传入参数本身是否为str这个类型对象,而非判断参数是否为字符串类型的实例。比如传入的"hi"是str类的实例,和str类本身的内存地址完全不同,所以这个判断永远为False。
  • 同理elif probe is int也存在相同问题,该分支永远无法触发,所有输入都会走到else分支,最终固定返回small int。
修复方案

有两种常用的修复方式,可根据使用场景选择:

方式1:用type()严格匹配类型

如果要求参数的类型完全等于指定类型、不允许子类匹配,可以用type()获取参数类型后做判断:

def check_it(probe):
    if type(probe) is str:
        return "a string"
    
    elif type(probe) is int and probe > 100:
        return "large int"
    else:
        return "small int"
    
print(check_it("hi")) # 输出预期结果 a string

方式2:用isinstance()判断(更推荐)

如果需要兼容子类继承场景(例如自定义str子类的实例也能识别为字符串),优先使用Python官方推荐的isinstance()方法:

def check_it(probe):
    if isinstance(probe, str):
        return "a string"
    
    elif isinstance(probe, int) and probe > 100:
        return "large int"
    else:
        return "small int"
    
print(check_it("hi")) # 输出预期结果 a string

内容的提问来源于stack exchange,提问作者Kirigaya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:06:07