1、獲取對象類型,基本類型可以用type()來判斷。
>>> type(123)
class 'int'>
>>> type('str')
class 'str'>
>>> type(None)
type(None) 'NoneType'>
2、如果想獲得一個對象的所有屬性和方法,可以使用dir()函數(shù)返回包含字符串的list。
>>> dir('ABC')
['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']
知識點(diǎn)擴(kuò)展:
使用type()
首先,我們來判斷對象類型,使用type()函數(shù):
基本類型都可以用type()判斷:
>>> type(123)
type 'int'>
>>> type('str')
type 'str'>
>>> type(None)
type 'NoneType'>
如果一個變量指向函數(shù)或者類,也可以用type()判斷:
>>> type(abs)
type 'builtin_function_or_method'>
>>> type(a)
class '__main__.Animal'>
但是type()函數(shù)返回的是什么類型呢?它返回type類型。如果我們要在if語句中判斷,就需要比較兩個變量的type類型是否相同:
>>> type(123)==type(456)
True
>>> type('abc')==type('123')
True
>>> type('abc')==type(123)
False
但是這種寫法太麻煩,Python把每種type類型都定義好了常量,放在types模塊里,使用之前,需要先導(dǎo)入:
>>> import types
>>> type('abc')==types.StringType
True
>>> type(u'abc')==types.UnicodeType
True
>>> type([])==types.ListType
True
>>> type(str)==types.TypeType
True
到此這篇關(guān)于python獲取對象信息的實(shí)例詳解的文章就介紹到這了,更多相關(guān)python如何獲取對象信息內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Python 可迭代對象 iterable的具體使用
- Python中可變和不可變對象的深入講解
- python面向?qū)ο笾惖睦^承詳解
- 簡單談?wù)凱ython面向?qū)ο蟮南嚓P(guān)知識
- Python面向?qū)ο笾蓡T相關(guān)知識總結(jié)
- Python面向?qū)ο笾畠?nèi)置函數(shù)相關(guān)知識總結(jié)
- python面向?qū)ο蟀鎸W(xué)生信息管理系統(tǒng)
- python面向?qū)ο蠡A(chǔ)之常用魔術(shù)方法
- python學(xué)習(xí)之可迭代對象、迭代器、生成器
- Python中的類對象示例詳解
- Python 的可變和不可變對象詳情