學習筆記 獲取物件資訊

2021-07-23 05:52:38 字數 1158 閱讀 8088

學習日期:2023年9月27日

學習課程:獲取物件資訊 - 廖雪峰的官方**

在本節中,我學習了可以通過type()或者isinstance()可以獲得和判斷物件的型別資訊,他們兩者的不同,在於type()不會認為子類是一種父類型別,isinstance()會認為子類是一種父類型別。

還學習了使用dir()可以獲得乙個物件的所有屬性和方法。使用getattr()setattr()hasattr()delsattr(),我們可以操作乙個物件的屬性和方法

因為type物件返回對應的class型別,如果要判斷乙個物件的型別是不是某乙個特定的型別的話就比較麻煩。

>>> 

import types

>>>

deffn

():...

pass

...>>> type(fn)==types.functiontype

true

>>> type(abs)==types.builtinfunctiontype

true

>>> type(lambda x: x)==types.lambdatype

true

>>> type((x for x in range(10)))==types.generatortype

true

如果classobject的父類,也會輸出true,但是如果classobject的子類,就會輸出false換句話說,isinstance()判斷的是乙個物件是否是該型別本身,或者位於該型別的父繼承鏈上。

通過getattr()setattr()hasattr()delasttr(),我們可以直接操作乙個物件的的屬性和方法。

python學習筆記 獲取物件資訊

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

筆記 python獲取物件資訊

拿到乙個物件的引用時,如何知道這個物件是什麼型別 有哪些方法?目錄 type isinstance dir type 函式返回對應的class型別。判斷乙個物件是否是函式用types模組中的各種型別作對比。import types def fn pass type fn types.function...

獲取物件資訊

print type 123 int print type abc str import types def fn pass print type fn types.functiontype print type abs types.builtinfunctiontype print type la...