Python 官方文档:入门教程 => 点击学习
1、获取对象类型,基本类型可以用type()来判断。 >>> type(123) <class 'int'> >>> type('str') <class '
1、获取对象类型,基本类型可以用type()来判断。
>>> type(123)
<class 'int'>
>>> type('str')
<class 'str'>
>>> type(None)
<type(None) 'NoneType'>
2、如果想获得一个对象的所有属性和方法,可以使用dir()函数返回包含字符串的list。
>>> dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']
知识点扩展:
使用type()
首先,我们来判断对象类型,使用type()函数:
基本类型都可以用type()判断:
>>> type(123)
<type 'int'>
>>> type('str')
<type 'str'>
>>> type(None)
<type 'NoneType'>
如果一个变量指向函数或者类,也可以用type()判断:
>>> type(abs)
<type 'builtin_function_or_method'>
>>> type(a)
<class '__main__.Animal'>
但是type()函数返回的是什么类型呢?它返回type类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同:
>>> type(123)==type(456)
True
>>> type('abc')==type('123')
True
>>> type('abc')==type(123)
False
但是这种写法太麻烦,python把每种type类型都定义好了常量,放在types模块里,使用之前,需要先导入:
>>> import types
>>> type('abc')==types.StringType
True
>>> type(u'abc')==types.UnicodeType
True
>>> type([])==types.ListType
True
>>> type(str)==types.TypeType
True
到此这篇关于Python获取对象信息的实例详解的文章就介绍到这了,更多相关python如何获取对象信息内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: python获取对象信息的实例详解
本文链接: https://www.lsjlt.com/news/11070.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0