python自省函式的總結 原始碼剖析

2021-07-07 06:30:19 字數 1877 閱讀 3184

#內建函式:getattr()、setattr()、delattr()、hasattr()
#getattr(object,name)確實和object.name是一樣的功能,只不過這裡可以把name作為乙個變數去處理

import statsout

#乙個模組支援多種不同格式的列印,根據傳入的formate引數的不同,呼叫不同的函式實現幾種格式的輸出

def output(data,format="text"):

outputfunc=getattr(statsout,"output%s"%format)#可以根據傳入output函式的format引數的不同 去呼叫statsout模組不同的方法(用格式化字串實現output%s)

return outputfunc

(data)#返回的是這個方法的物件 就可以直接使用了 如果要新增新的格式 只需要在模組中寫入新的方法函式

#在呼叫output函式時使用新的引數就可以使用不同的格式輸出

#獲取物件引用getattr getattr用於返回乙個物件屬性,或者方法

class rocket:

def __init__(self):

self.name="zhouruifu"

self.age=23

def method(self):

print "method print...."

roc=rocket()

print roc.name,roc.age

roc.method()

#上下兩種效果等同

print getattr(roc,"name","this property does not exist...")#如果roc物件中有屬性name則列印self.name的值,否則列印 this property does not exist

print getattr(roc,"name111","this property does not exist...")

print getattr(roc,'age',"this property does not exist...")

print getattr(roc,'age222',"this property does not exist...")

print getattr(roc,"method","this property does not exist...")

print getattr(roc,"method333","this property does not exist...")

getattr(roc,"method",'default...')()#如果有方法method,執行函式並列印none 否則列印default

#setattr()

class rocket:

def __init__(self,name):

self.name=name

roc=rocket("zhouruifu")

setattr(roc,"zhouruifu",23)#等價於 roc.zhouruifu=23

print roc.name

print roc.zhouruifu

print hasattr(roc,"name")#存在此屬性 輸出true

#delattr() 引數是由乙個物件(記住python中一切皆是物件)和乙個字串組成的。string引數必須是物件屬性名之一。該函式刪除該obj的乙個由string指定的屬性

delattr(roc,"name") #等價於del roc.name

#hasattr() 用於確定乙個物件是否具有某個屬性

print hasattr(roc,"name")#物件屬性被刪除後輸出false

ConcurrentHashMap的原始碼分析

put final v putval k key,v value,boolean onlyifabsent 在上一步的else if中 f 不為null時,則判斷f的hash值是否為moved,即 1,如果為 1,表示正在擴容 else if fh f.hash moved 協助資料遷移 tab h...

DispatcherServlet的原始碼和流程分析

1 自動配置dispatcherservlet和dispatcherservletregistry 2 註冊dispatcherservlet到servletcontext 3 初始化mvc的元件 handler執行完成後,向dispatcherservlet 返回乙個modelandview物件 ...

python的自省機制

1 自省 自省就是物件導向的語言所寫的程式在執行時,能夠知道物件的型別。簡單一句就是,執行時能夠獲知物件的型別。2 自省機制 自省機制通過函式實現,是乙個函式。例如python,buby,object c,c 都有自省的能力,這裡面的c 的自省的能力最弱,只能夠知道是什麼型別,而像python可以知...