python 内建函数 type() 和 isinstance() 介绍
Python 不支持方法或函数重载, 因此你必须自己保证调用的就是你想要的函数或对象。一个名字里究竟保存的是什么?相当多,尤其是这是一个类型的名字时。确认接收到的类型对象的身份有很多时候都是很有用的。为了达到此目的,Python 提供了一个内建函数type(). type()返回任意Python 对象对象的类型,而不局限于标准类型。让我们通过交互式解释器来看几个使用type()内建函数返回多种对象类型的例子:
1 >>> type('') 2 <type 'str'> 3 >>> 4 >>> s = 'xyz' 5 >>> type(s) 6 <type 'str'> 7 >>> 8 >>> type(100) 9 <type 'int'> 10 >>> type(0+0j) 11 <type 'complex'> 12 >>> type(0L) 13 <type 'long'> 14 >>> type(0.0) 15 <type 'float'> 16 >>> 17 >>> type([]) 18 <type 'list'> 19 >>> type(()) 20 <type 'tuple'> 21 >>> type({}) 22 <type 'dict'> 23 >>> type(type) 24 <type 'type'> 25 >>> 26 >>> class Foo: pass # new-style class 27 ... 28 >>> foo = Foo() 29 >>> class Bar(object): pass # new-style class 30 ... 31 >>> bar = Bar() 32 >>> 33 >>> type(Foo) 34 <type 'classobj'> 35 >>> type(foo) 36 <type 'instance'> 37 >>> type(Bar) 38 <type 'type'> 39 >>> type(bar) 40 <class '__main__.Bar'>
Python2.2 统一了类型和类, 如果你使用的是低于Python2.2 的解释器,你可能看到不一样的输出结果。
1 >>> type('') 2 <type 'string'> 3 >>> type(0L) 4 <type 'long int'> 5 >>> type({}) 6 <type 'dictionary'> 7 >>> type(type) 8 <type 'builtin_function_or_method'> 9 >>> 10 >>> type(Foo) # assumes Foo created as in above 11 <type 'class'> 12 >>> type(foo) # assumes foo instantiated also 13 <type 'instance'>
如果觉得对您有帮助,麻烦您点一下推荐,谢谢!
好记忆不如烂笔头
好记忆不如烂笔头
分类:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术