【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 ...
随机推荐
- oracle的事务隔离级别和读一致性
oracle提供了三个隔离级别: 1.读提交 ,简而言之只能读取语句开始执行前提交的数据 2.串行,这个好理解,就是事务串行运行,避免经典的三个场景-脏读.不可重复读.幻读. 3.只读,oracle已 ...
- mysql 中的存储过程
创建一个简单的存储过程 存储过程proc_adder功能很简单,两个整型输入参数a和b,一个整型输出参数sum,功能就是计算输入参数a和b的结果,赋值给输出参数sum: 几点说明: DELIMITER ...
- SI - 系统 - 操作系统简述 (Operating System)
Unix 操作系统:System V.BSD Microsoft Windows Apple Mac OS Linux FreeBSD 安装 https://jingyan.baidu.com/art ...
- iOS中出现"Check dependenciesWarning: The Copy Bundle Resources build phase contains this target's Info.plist file..."的解决办法A
出现场景 项目中移除info.plist ,后来又重新拖拽回来,同时勾选了Copy items if needed 解决办法 1.删除(删除时选择Remove Reference) 2.重新添加i ...
- 虚拟机服务没有启动的 CentOS 和 Ubuntu 无法上网
测试用 vmware 安装 OSX,安装补丁时要停止 vmware 的服务.如下图: 结果忘记启动了,导致 centos\ubuntu 等所有虚拟机都无法上网...所有的 启动这四个服务后,一切恢复正 ...
- ubuntu64位运行32位程序
sudo dpkg --add-architecture i386 sudo apt install libc6:i386 转:https://blog.csdn.net/zoomdy/article ...
- hadoop jar x.jar 执行过程
hadoop jar x.jar 执行过程 Yarn框架执行内容 1,job.waitforcompletion() 启动 Runjar 进程 -> Resourcemanage申请一个j ...
- PHP HashTable总结
本篇文章主要是对 PHP HashTable 总结,下面的参考链接是很好的学习资料. 总结 HashTable 又叫做散列表,是一种用于以常数平均时间执行插入.删除和查找的技术.不能有效的支持元素之间 ...
- SXOI2018游记
day0 动身去太原.太原五中虽然挺小的但是很好看啊qwq(进门口一个"通天堂"(逃 试机.似乎看到了__stdcall!!然而没敢去认orz.linux选手似乎是9个.准考证(一 ...
- nginx error_page
1. error_page语法 语法: error_page code [ code... ] [ = | =answer-code ] uri | @named_location 默认值: no 使 ...