确定Python变量是否是内置类型的实例 [英] Determine if Python variable is an instance of a built-in type

查看:91
本文介绍了确定Python变量是否是内置类型的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定给定的Python变量是否是本机类型的实例:strintfloatboollistdict等.有优雅的方法吗?

I need to determine if a given Python variable is an instance of native type: str, int, float, bool, list, dict and so on. Is there elegant way to doing it?

或者这是唯一的方法:

if myvar in (str, int, float, bool):
    # do something

推荐答案

实现此目的的最佳方法是在称为primitiveTypes的元组列表中收集类型,并且:

The best way to achieve this is to collect the types in a list of tuple called primitiveTypes and:

if isinstance(myvar, primitiveTypes): ...

types模块包含所有有助于构建的重要类型的集合列表/元组.

The types module contains collections of all important types which can help to build the list/tuple.

从Python 2.2开始可以正常工作

这篇关于确定Python变量是否是内置类型的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆