python 獲取物件資訊的方法

2021-08-06 05:30:15 字數 2622 閱讀 1865

1、type() 返回對應的class型別

例如:

>>> type(123)==type(456)

true

>>> type(123)==int

true

>>> type('abc')==type('123')

true

>>> type('abc')==str

true

>>> type('abc')==type(123)

false

2、isinstance()   對於class的繼承關係來說,使用type()就很不方便。我們要判斷class的型別,可以使用isinstance()函式。

object -> animal -> dog -> husky
>>> a = animal()>>> d = dog()>>> h = husky()
>>> isinstance(h, husky)

true

>>> isinstance('a', str)

true

>>> isinstance(123, int)

true

>>> isinstance(b'a', bytes)

true

>>> isinstance([1, 2, 3], (list, tuple))

true

>>> isinstance((1, 2, 3), (list, tuple))

true

3、dir()要獲得乙個物件的所有屬性和方法,可以使用dir()函式

>>> 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']

4、配合getattr()setattr()以及hasattr(),我們可以直接操作乙個物件的狀態:

>>> hasattr(obj, 'x') # 有屬性'x'嗎?

true

>>> obj.x

9>>> hasattr(obj, 'y') # 有屬性'y'嗎?

false

>>> setattr(obj, 'y', 19) # 設定乙個屬性'y'

>>> hasattr(obj, 'y') # 有屬性'y'嗎?

true

>>> getattr(obj, 'y') # 獲取屬性'y'

19>>> obj.y # 獲取屬性'y'

19

>>> hasattr(obj, 'power') # 有屬性'power'嗎?

true

>>> getattr(obj, 'power') # 獲取屬性'power'

0x10077a6a0>>

>>> fn = getattr(obj, 'power') # 獲取屬性'power'並賦值到變數fn

>>> fn # fn指向obj.power

0x10077a6a0>>

>>> fn() # 呼叫fn()與呼叫obj.power()是一樣的

81

python檢視物件的方法 獲取物件資訊

當我們拿到乙個物件的引用時,如何知道這個物件是什麼型別 有哪些方法呢?使用type 首先,我們來判斷物件型別,使用type 函式 基本型別都可以用type 判斷 type 123 type str type none 如果乙個變數指向函式或者類,也可以用type 判斷 type abs type a...

python 獲取物件資訊

判斷物件型別,使用type 函式 判斷乙個物件是否是函式 使用types模組中定義的常量 import types type abs types.builtinfunctiontype true type lambda x x types.lambdatype true type x for x i...

python中獲取物件資訊

拿到乙個變數,除了用isinstance 判斷它是否是某種型別的例項外,還有沒有別的方法獲取到更多的資訊呢?例如,已有定義 class person object def init self,name,gender self.name name self.gender gender class st...