The Python getattr Function

Python年代getattr函數用於獲取一個屬性的對象,使用字符串對象,而不是一個標識符識別屬性。換句話說,如下兩個語句是等價的 python

value = obj.attribute
value = getattr(obj, "attribute")

若是屬性存在,返回相應的值。若是屬性不存在,你獲得一個AttributeError異常。 ide

The getattr function can be used on any object that supports dotted notation (by implementing the __getattr__ method). This includes class objects, modules, and even function objects. 函數

getattr函數可用於任何支持點狀符號的對象(經過實現__getattr__方法)。這包括類對象、模塊和函數對象 spa

path = getattr(sys, "path")
doc = getattr(len, "__doc__")

The getattr function uses the same lookup rules as ordinary attribute access, and you can use it both with ordinary attributes and methods: code

getattr函數使用相同的查詢規則做爲普通屬性訪問,您能夠使用它與普通的屬性和方法 對象

result = obj.method(args)

func = getattr(obj, "method")
result = func(args)

or, in one line: 字符串

result = getattr(obj, "method")(args)

Calling both getattr and the method on the same line can make it hard to handle exceptions properly. To avoid confusing AttributeError exceptions raised by getattr with similar exceptions raised inside the method, you can use the following pattern: get

調用getattr和方法在同一行,那就很難正確地處理異常。爲了不混淆AttributeError異常提出getattr具備相似方法拋出的異常,您能夠使用如下模式 it

try:
    func = getattr(obj, "method") except AttributeError:
    ... deal with missing method ... else:
    result = func(args)

The function takes an optional default value, which is used if the attribute doesn’t exist. The following example only calls the method if it exists: io

函數接受一個可選的默認值,若是該屬性不存在使用。下面的例子只調用該方法若是它存在

func = getattr(obj, "method", None) if func:
    func(args)

Here’s a variation, which checks that the attribute is indeed a callable object before calling it.

年代的一個變種,檢查屬性在調用以前確實是一個可調用對象。

func = getattr(obj, "method", None) if callable(func):
    func(args)
相關文章
相關標籤/搜索