Python基礎(獲取物件資訊)

2022-09-01 19:24:13 字數 2033 閱讀 4211

import

types

print(type('

abc') == str)#

true

print(type(123) == int)#

true

deff1():

pass

print(type(f1) == types.functiontype)#

true

print(type(abs) == types.builtinfunctiontype)#

true

print(type(lambda x:x) == types.lambdatype)#

true

print(type(x for x in range(0,11)) == types.generatortype)#

true

#isinstance()判斷的是乙個物件是否是該型別本身,或者位於該型別的父繼承鏈上,總是優先使用isinstance()判斷型別,可以將指定型別及其子類「一網打盡」

print(isinstance(b'

b',bytes))#

true

print(isinstance([1,2,3],(list,tuple)))#

true 乙個變數是否是某些型別中的一種

#獲得乙個物件的所有屬性和方法,可以使用dir()函式,它返回乙個包含字串的list

print(dir('

abc'))#

['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']

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

class

f1(object):

def__init__

(self,num):

self.

__num__ =num

defget_num(self):

return self.__num__

f1 = f1(300)

print(hasattr(f1,'

__num__

'))#

true

setattr(f1,'

x',200)#

設定乙個屬性'x'

print(getattr(f1,'

x'))#

200print(getattr(f1,'

get_num

'))#

> 可以獲得物件的方法

#print(f1.x)#x只是新增到了例項f1的屬性裡,沒有新增在f1的屬性裡

#定義了乙個類屬性後,這個屬性雖然歸類所有,但類的所有例項都可以訪問到

class

student(object):

name = '

student

's = student() #

建立例項s

print(s.name) #

student 列印name屬性,因為例項並沒有name屬性,所以會繼續查詢class的name屬性

print(student.name) #

student列印類的name屬性

s.name = '

michael'#

給例項繫結name屬性

print(s.name) #

michael 由於例項屬性優先順序比類屬性高,因此,它會遮蔽掉類的name屬性

print(student.name) #

student 但是類屬性並未消失,用student.name仍然可以訪問

del s.name #

如果刪除例項的name屬性

print(s.name) #

student 再次呼叫s.name,由於例項的name屬性沒有找到,類的name屬性就顯示出來了

#不要對例項屬性和類屬性使用相同的名字,因為相同名稱的例項屬性將遮蔽掉類屬性,但是當你刪除例項屬性後,再使用相同的名稱,訪問到的將是類屬性

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...

筆記 python獲取物件資訊

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