天天看点

python getattr两个括号_Python getattr()用法及代碼示例

getattr()函數用於訪問對象的屬性值,還提供在 key 不可用時執行默認值的選項。這在檢查Web開發以及day-to-day編程的許多其他階段中可用的 key 方麵具有更大的應用程序。

語法:getattr(obj,key,def)參數:obj:需要處理其屬性的對象。關鍵字:對象的屬性def:如果未找到該屬性,則需要打印的默認值。返回:如果值可用,則返回對象值;如果不存在case屬性,則返回默認值;如果不存在屬性且未指定默認值,則返回AttributeError。

代碼1:演示getattr()的工作

# Python code to demonstrate

# working of getattr()

# declaring class

class GfG:

name = "GeeksforGeeks"

age = 24

# initializing object

obj = GfG()

# use of getattr

print("The name is " + getattr(obj,'name'))

# use of getattr with default

print("Description is " + getattr(obj, 'description' , 'CS Portal'))

# use of getattr without default

print("Motto is " + getattr(obj, 'motto'))

輸出:

The name is GeeksforGeeks

Description is CS Portal

異常:

AttributeError: GfG instance has no attribute 'motto'

代碼2:性能分析

# Python code to demonstrate

# performance analysis of getattr()

import time

# declaring class

class GfG:

name = "GeeksforGeeks"

age = 24

# initializing object

obj = GfG()

# use of getattr to print name

start_getattr = time.time()

print("The name is " + getattr(obj,'name'))

print("Time to execute getattr " + str(time.time() - start_getattr))

# use of conventional method to print name

start_obj = time.time()

print("The name is " + obj.name)

print("Time to execute conventional method " + str(time.time() - start_obj))

輸出:

The name is GeeksforGeeks

Time to execute getattr 5.0067901611328125e-06

The name is GeeksforGeeks

Time to execute conventional method 1.1920928955078125e-06

結果:常規方法比getattr()花費的時間更少,但是如果在缺少屬性的情況下必須使用默認值,則getattr()是一個不錯的選擇。

應用範圍:getattr()的許多應用程序,在缺少對象屬性的情況下(在某些表單屬性是可選的Web開發中)很少提及。在機器學習功能集合的情況下,如果某些功能有時在數據收集中丟失,也很有用。