其實看了getattr 的解釋一直不知道到底該怎么用才好,心想這直接呼叫就好干嘛這么麻煩
getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case.最近看了drf的原始碼才明白:
if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed
簡單來說 getattr就是能吧原先原先物件點屬性,或者物件點方法換成物件點任意字串的操作,正常來說物件點一個字串肯定會報錯的,getattr操作就在這個字串也可以是一個變數不必須是類里面的方法
舉一個栗子
例如一個需求要呼叫一些物件里面的方法,但在有的方法 a物件有b物件沒有, a物件象封裝了另一種功能功能b物件封裝了另一種功能 ,他們共同完成一件事,現在要能夠讓請求的時候自動呼叫該呼叫物件方法 一般操作就是 判斷物件然后分別呼叫可以調喲的方法,需要寫大量的判段,不然程式無法執行例如這樣:class A(object):
def get(self):
print("執行get方法")
pass
class B(object):
def post(self):
print("執行post方法")
pass
aobj = A()
bobj = B()
objlist = [aobj, bobj]
for obj in objlist: #必然會報錯 obj.get() obj.post()
使用gettattr后:
class A(object):
def get(self):
print("執行get方法")
pass
class B(object):
def post(self):
print("執行post方法")
pass
aobj = A()
bobj = B()
objlist = [aobj, bobj]
for i in objlist:
funname = 'post'
handle = getattr(i, funname, None)
if handle:
handle()
getattr(self,Name ,None) 如果沒有這些方法就回傳None,要是沒有這個引數就會觸發例外
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/146285.html
標籤:Python
