【Python】Python—判断变量的基本类型
type()
>>> type(123)==type(456)
True
>>> type(123)==int
True
>>> type('abc')==type('123')
True
>>> type('abc')==str
True
>>> type('abc')==type(123)
False
isinstance()
>>> isinstance('a', str)
True
>>> isinstance(123, int)
True
>>> isinstance(b'a', bytes)
True
dir()
如果要获得一个对象的所有属性和方法,可以使用dir()
函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:
>>> dir('ABC')
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Python在定义变量的时候不用指明具体的的类型,解释器会在运行的时候会自动检查 变量的类型,并根据需要进行隐式的类型转化。因为Python是动态语言,所以一般情 况下是不推荐进行类型转化的。比如"+"操作时,如果加号两边是数据就进行加法操 作,如果两边是字符串就进行字符串连接操作,如果两边是列表就进行合并操作,甚 至可以进行复数的运算。解释器会在运行时根据两边的变量的类型调用不同的内部方法。 当加号两边的变量类型不一样的时候,又不能进行类型转化,就会抛出TypeError的异常。
但是在实际的开发中,为了提高代码的健壮性,我们还是需要进行类型检查的。而进行 类型检查首先想到的就是用type(),比如使用type判断一个int类型。
- import types
- if type(1) is types.Integer:
- print('1是int类型')
- else:
- print('1不是int类型')
上面的程序会输出:1是int类型
我们在types中可以找到一些常用的类型,在2.7.6中显示的结果:
- types.BooleanType # bool类型
- types.BufferType # buffer类型
- types.BuiltinFunctionType # 内建函数,比如len()
- types.BuiltinMethodType # 内建方法,指的是类中的方法
- types.ClassType # 类类型
- types.CodeType # 代码块类型
- types.ComplexType # 复数类型
- types.DictProxyType # 字典代理类型
- types.DictType # 字典类型
- types.DictionaryType # 字典备用的类型
- types.EllipsisType
- types.FileType # 文件类型
- types.FloatType # 浮点类型
- types.FrameType
- types.FunctionType # 函数类型
- types.GeneratorType
- types.GetSetDescriptorType
- types.InstanceType # 实例类型
- types.IntType # int类型
- types.LambdaType # lambda类型
- types.ListType # 列表类型
- types.LongType # long类型
- types.MemberDescriptorType
- types.MethodType # 方法类型
- types.ModuleType # module类型
- types.NoneType # None类型
- types.NotImplementedType
- types.ObjectType # object类型
- types.SliceTypeh
- types.StringType # 字符串类型
- types.StringTypes
- types.TracebackType
- types.TupleType # 元组类型
- types.TypeType # 类型本身
- types.UnboundMethodType
- types.UnicodeType
- types.XRangeType
在Python 3中,类型已经明显减少了很多
- types.BuiltinFunctionType
- types.BuiltinMethodType
- types.CodeType
- types.DynamicClassAttribute
- types.FrameType
- types.FunctionType
- types.GeneratorType
- types.GetSetDescriptorType
- types.LambdaType
- types.MappingProxyType
- types.MemberDescriptorType
- types.MethodType
- types.ModuleType
- types.SimpleNamespace
- types.TracebackType
- types.new_class
- types.prepare_class
但是我们并不推荐使用type来进行类型检查,之所以把这些类型列出来,也是为了扩展知识 面。那为什么不推荐使用type进行类型检查呢?我们来看一下下面的例子。
- import types
- class UserInt(int):
- def __init__(self, val=0):
- self.val = int(val)
- i = 1
- n = UserInt(2)
- print(type(i) is type(n))
上面的代码输出:False
这就说明i和n的类型是不一样的,而实际上UserInt是继承自int的,所以这个判断是存在问题的, 当我们对Python内建类型进行扩展的时候,type返回的结果就不够准确了。我们再看一个例子。
- class A():
- pass
- class B():
- pass
- a = A()
- b = B()
- print(type(a) is type(b))
代码的输出结果: True
type比较的结果a和b的类型是一样的,结果明显是不准确的。这种古典类的实例,type返回的结果都 是一样的,而这样的结果不是我们想要的。对于内建的基本类型来说,使用tpye来检查是没有问题的, 可是当应用到其他场合的时候,type就显得不可靠了。这个时候我们就需要使用isinstance来进行类型 检查。
- isinstance(object, classinfo)
object表示实例,classinfo可以是直接或间接类名、基本类型或者有它们组成的元组。
- >>> isinstance(2, float)
- False
- >>> isinstance('a', (str, unicode))
- True
- >>> isinstance((2, 3), (str, list, tuple))
- True
【Python】Python—判断变量的基本类型的更多相关文章
- Python如何判断变量的类型
Python判断变量的类型有两种方法:type() 和 isinstance() 如何使用 对于基本的数据类型两个的效果都一样 type() ip_port = ['219.135.164.245', ...
- python中判断变量的类型
python的数据类型有:数字(int).浮点(float).字符串(str),列表(list).元组(tuple).字典(dict).集合(set) 一般通过以下方法进行判断: 1.isinstan ...
- Python—判断变量的基本类型
type() >>> type(123)==type(456) True >>> type(123)==int True >>> type('ab ...
- Python 入门学习 -----变量及基础类型(元组,列表,字典,集合)
Python的变量和数据类型 1 .python的变量是不须要事先定义数据类型的.能够动态的改变 2. Python其中一切皆对象,变量也是一个对象,有自己的属性和方法 我们能够通过 来查看变量的类型 ...
- Python学习--判断变量的数据类型
import types aaa = 0 print type(aaa) if type(aaa) is types.IntType: print "the type of aaa is i ...
- Python中的变量、引用、拷贝和作用域
在Python中,变量是没有类型的,这和以往看到的大部分编辑语言都不一样.在使用变量的时候,不需要提前声明,只需要给这个变量赋值即可.但是,当用变量的时候,必须要给这个变量赋值:如果只写一个变量,而没 ...
- 判断javaScript变量是Ojbect类型还是Array类型
JavaScript是弱类型的语言,所以对变量的类型并没有强制控制类型.所以声明的变量可能会成为其他类型的变量, 所以在使用中经常会去判断变量的实际类型. 对于一般的变量我们会使用typeof来判 ...
- JavaScript判断变量数据类型
一.JS中的数据类型 1.数值型(Number):包括整数.浮点数. 2.布尔型(Boolean) 3.字符串型(String) 4.对象(Object) 5.数组(Array) 6.空值(Null) ...
- Python学习笔记:输入输出,注释,运算符,变量,数字类型,序列,条件和循环控制,函数,迭代器与生成器,异常处理
输入输出 输入函数input()和raw_input() 在Python3.x中只有input()作为输入函数,会将输入内容自动转换str类型: 在Python2.x中有input()和raw_inp ...
随机推荐
- ubuntu多版本php切换
最近想要学习一下swoole,虽然机子上装的是php7.0,但是考虑到一些有关swoole的轮子要依赖更高版本(例如swooletw),所以就在机子上升级了php7.2,下面是在网上搜索或者自己折腾出 ...
- MySQL单表数据查询(DQL)
数据准备工作: CREATE TABLE student( sid INT PRIMARY KEY AUTO_INCREMENT, sname ), age TINYINT, city ), scor ...
- Java : java基础(2) 集合&正则&异常&File类
Obj 方法: hashCode() 返回内存地址值, getClass() 返回的时运行时类, getName() 返回类名, toString() 把名字和hashCode() 合在一起返回,如果 ...
- Linux 新建定时任务
Linux 新建定时任务: 1.查看指定用户列表: crontab -u apache -l 2.切换至对应用户,这里是apache su apache 3.新增定时任务: crontab -e 写入 ...
- 官方yum源安装选择所需版本mysql数据库并初始化(yum默认安装的是最新版MySQL8.+)
在官网是找不到5.x系列的域名源的,系统默认是安装的oracle数据库,在安装前需要删除默认的 以下教程来源于官网说明 先去官网下载yum源,地址 https://dev.mysql.com/down ...
- R语言学习笔记(一):mode, class, typeof的区别
要了解这三个函数的区别,先了解numeric, double与integer. 在r中浮点数有两个名字叫numeric与double. double是指它的类型(type)名字,numeric是指它的 ...
- [POJ1785]Binary Search Heap Construction(笛卡尔树)
Code #include <cstdio> #include <algorithm> #include <cstring> #define N 500010 us ...
- [JSOI2007] 建筑抢修 (贪心 + 优先队列)
小刚在玩JSOI提供的一个称之为“建筑抢修”的电脑游戏:经过了一场激烈的战斗,T部落消灭了所有z部落的入侵者.但是T部落的基地里已经有N个建筑设施受到了严重的损伤,如果不尽快修复的话,这些建筑设施将会 ...
- 【Leetcode】709. To Lower Case
To Lower Case Description Implement function ToLowerCase() that has a string parameter str, and retu ...
- Android面试收集录 数据库
1.SQLite数据库如何查询表table1的第20条到30条记录? select * from table1 limit 19,11 ==>从19开始,11个数据 2.如何才能将table ...