【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 ...
随机推荐
- hdu_3123_GCC
The GNU Compiler Collection (usually shortened to GCC) is a compiler system produced by the GNU Proj ...
- ABAP术语-Purchase Order
Purchase Order 原文:http://www.cnblogs.com/qiangsheng/archive/2008/03/07/1094717.html Request or instr ...
- PC时代 常用搜索引擎高级指令 勿忘
PC时代,高级指令辅助检索,高效输出既定的需求,被广泛运用于Search Engine. 布局search入口的平台,高级指令都不可或缺.现今,高级指令的高效性,仍然主要体现在搜索引擎检索过程中. i ...
- 某CTF收集的Mysql爆表、爆字段语句
Mysql特性 获取数据库名未知函数可爆数据库名 FUNCTION youcanneverfindme17.a does not exist 获取表名and linestring(pro_id) ...
- webug学习(1)
webug的题目,比较简单,拿来巩固一哈. 1. 一看就知道是注入漏洞了,啥也不说sqlmap直接开炮. 先-u 之后-u 网址 --current-db 获取当前网址的数据库 所以当前数据库就是 p ...
- Python爬虫爬取豆瓣电影之数据提取值xpath和lxml模块
工具:Python 3.6.5.PyCharm开发工具.Windows 10 操作系统.谷歌浏览器 目的:爬取豆瓣电影排行榜中电影的title.链接地址.图片.评价人数.评分等 网址:https:// ...
- HyperLedger Fabric 1.4 区块链开发平台(4.1)
目前区块链开发平台分“公有链平台”和“联盟链系统”两类,“公有链平台”主要以以太坊为主的平台,可以在该类平台上进行代币的发行和根据各种模块搭建应用:“联盟链系统”主要以超级账本为主的开源系统,该类开源 ...
- R语言学习笔记(十二):零碎知识点(31-35)
31--round(),floor()和ceiling() round()四舍五入取整 floor()向下取整 ceiling()向上取整 > round(3.5) [1] 4 > flo ...
- 开启TCP BBR拥塞控制算法
原文来自:https://github.com/iMeiji/shadowsocks_install/wiki/%E5%BC%80%E5%90%AFTCP-BBR%E6%8B%A5%E5%A1%9E% ...
- 响应式js设置
<script> (function anonymous() { // 声明一个函数,并直接的执行 function computed() { let HTML = document.do ...