确定Python变量是否是内置类型的实例 [英] Determine if Python variable is an instance of a built-in type
本文介绍了确定Python变量是否是内置类型的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要确定给定的Python变量是否是本机类型的实例:str
,int
,float
,bool
,list
,dict
等.有优雅的方法吗?
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变量是否是内置类型的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文