Python 中的类型判断方法

Python 提供了多种类型判断方法,每种方法的场景也不同。主要分为类型检查(运行时判断) 和**类型提示(静态检查)**两大类。

一、运行时类型判断

1. type():查看对象类型

type() 返回对象的确切类型。

复制代码
print(type(42))          # <class 'int'>
print(type(3.14))        # <class 'float'>
print(type("hello"))     # <class 'str'>
print(type([1, 2, 3]))   # <class 'list'>
print(type({"a": 1}))    # <class 'dict'>

# 判断是否等于某个类型
if type(value) == int:
    print("这是整数")

注意 :type() 在继承关系中不会考虑子类,它返回的是对象的具体类型,而不是继承链。

复制代码
class Animal:
    pass

class Dog(Animal):
    pass

dog = Dog()
print(type(dog))         # <class '__main__.Dog'>
print(type(dog) == Dog)  # True
print(type(dog) == Animal)  # False(Dog 不是 Animal)

2. isinstance():判断是否属于某个类型(推荐)

isinstance() 会检查对象的类型是否与指定类型匹配,包括父类。

复制代码
class Animal:
    pass

class Dog(Animal):
    pass

dog = Dog()

print(isinstance(dog, Dog))      # True
print(isinstance(dog, Animal))   # True(Dog 是 Animal 的子类)
print(isinstance(dog, object))   # True(所有类都继承 object)
print(isinstance(42, int))       # True
print(isinstance(42, (int, float)))# True(元组表示任一类型)
方法 是否考虑继承关系 推荐度
type(obj) == cls 不考虑 不推荐
isinstance(obj, cls) 考虑 推荐

3. issubclass():判断类继承关系

复制代码
class Animal:
    pass

class Dog(Animal):
    pass

class Cat(Animal):
    pass

print(issubclass(Dog, Animal))   # True
print(issubclass(Cat, Animal))   # True
print(issubclass(Dog, Cat))      # False
print(issubclass(Dog, (Cat, Animal)))  # True(任一匹配)

4. callable():判断是否可调用

复制代码
def my_func():
    pass

class MyClass:
    def method(self):
        pass

print(callable(my_func))    # True
print(callable(MyClass))    # True
print(callable(MyClass.method))  # True(未绑定的方法)
print(callable(42))         # False
print(callable("hello"))    # False

5. 检查可迭代对象

复制代码
from collections.abc import Iterable

print(isinstance([1, 2, 3], Iterable))  # True
print(isinstance("hello", Iterable))    # True
print(isinstance(42, Iterable))         # False

对比总结

方法 用途 适用场景
type(obj) 获取对象的确切类型 需要精确判断类型时
isinstance(obj, cls) 判断对象是否属于某个类型(包括父类) 推荐,大多数场景
issubclass(cls1, cls2) 判断类继承关系 检查类是否派生自另一个类
callable(obj) 判断对象是否可调用 检查函数、方法等
hasattr(obj, attr) 判断对象是否有某个属性/方法 鸭子类型检查
type hints 类型注解 静态类型检查(不运行)
相关推荐
weixin_3077791317 分钟前
Jupyter SQL 表血缘分析并导出 Excel
开发语言·python·sql·算法·excel
benchmark_cc17 分钟前
如何用 Python 计算盈亏痛苦比(Gain-to-Pain Ratio)?
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
sbjdhjd17 分钟前
后端编程语言 PHP 笔记(第 1–3 章)|PHP 简介、版本与运行环境安装
开发语言·人工智能·笔记·后端·python·ai·php
Ivanqhz36 分钟前
wb 自动化搬运矩阵: 一条定型 “芯片选型偏好” 的话术?!
人工智能·python·机器学习
小白的高手之路37 分钟前
【LeetCode 热题 100】240. 搜索二维矩阵 II|矩阵、二分查找、Z 字形查找(Python)
python·算法·leetcode·矩阵·力扣
geovindu41 分钟前
python:DBSCAN
开发语言·后端·python·算法
斯内普吖1 小时前
(开源)智慧物业管理系统实战指南 基于 Python + Django + uni-app + Vue + MySQL
vue.js·python·django·uni-app·开源
Ponp_8 小时前
用 StyleGAN2 做图像数据扩充实战
python·深度学习·生成对抗网络
富贵儿99812 小时前
NL2SQL 实践手记 08:SQL 没报错,答案为什么不对——从失败复盘到 Workflow 修复
数据库·python·sql·ai·自然语言处理·langchain