You need to enable JavaScript to run this app. Python中是否有类似JavaScript typeof的查询变量类型的函数?
优惠活动
大模型
产品
解决方案
定价
更多

Python中是否有类似JavaScript typeof的查询变量类型的函数?

Python 变量类型查询方法

Python 有原生支持的变量类型查询能力,功能完全可以覆盖 JavaScript 中 typeof variable 的使用场景,常用的有两个函数:

1. type() 函数

最直接对应 JS typeof 的功能,会返回变量的精确类型对象:

# 示例
num = 100
print(type(num))  # 输出 <class 'int'>

str_val = "测试文本"
print(type(str_val))  # 输出 <class 'str'>

list_val = [1, 2, 3]
print(type(list_val))  # 输出 <class 'list'>

2. isinstance() 函数

如果你的需求是判断变量是否属于某一指定类型,更推荐用这个函数,它支持继承关系的判断,使用场景更灵活:

# 示例
class A:
    pass
class B(A):
    pass

obj = B()
print(isinstance(obj, B))  # 输出 True
print(isinstance(obj, A))  # 输出 True,因为B继承自A

两个函数的区别

  • type() 仅返回变量的精确类型,适合你需要明确知晓变量所属具体类型的场景
  • isinstance() 会识别类的继承关系,适合做类型合法性校验的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 16:00:02