Python getattr() 作用 用于访问对象的属性值,还提供了在密钥不可用时执行默认值的选项。
null
语法: getattr(对象、键、定义)
参数:
- obj: 需要处理其属性的对象。
- 关键: 对象的属性
- def: 在未找到属性的情况下需要打印的默认值。
返回: 对象值如果值可用,则默认值为case属性不存在 如果属性不存在且默认值不存在,则返回AttributeError 明确规定。
getattr()在Python中的工作原理
例1: 演示getattr()的工作原理
Python3
# Python code to demonstrate # working of getattr() # declaring class class GfG: name = "GeeksforGeeks" age = 24 # initializing object and # python getattr() function call 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 GeeksforGeeksDescription is CS Portal
例外情况:
AttributeError: GfG instance has no attribute 'motto'
例2: 找不到命名属性时的getattr()
Python3
# Python code to demonstrate # working of getattr() # declaring class class GfG: name = "GeeksforGeeks" age = 24 # initializing object obj = GfG() # use of getattr without default print ( "Gender is " + getattr (obj, 'gender' )) |
输出:
AttributeError: 'GfG' object has no attribute 'gender'
示例3:性能分析和带有参数的getattr python
Python3
# 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 GeeksforGeeksTime to execute getattr 5.0067901611328125e-06The name is GeeksforGeeksTime to execute conventional method 1.1920928955078125e-06
示例4:getattr Python默认值
Python3
# Python code to demonstrate # working of getattr() # declaring class class GfG: name = "GeeksforGeeks" age = 24 # initializing object obj = GfG() # use of getattr without default print ( "Motto is " + getattr (obj, 'motto' )) |
输出:
AttributeError: 'GfG' object has no attribute 'motto'
示例5:Python getattr()函数调用
Python3
# Python code to demonstrate # working of getattr() # declaring class class GfG: def __init__( self , name, age): self .name = name self .age = age def call( self , x): print (f "{self.name} called with parameters '{x}'" ) return # initializing object obj = GfG( "Vivek" , 10 ) print (obj) print (GfG) print ( getattr (obj, 'call' )) getattr (obj, 'call' )( 'arg' ) |
输出:
<__main__.GfG object at 0x0000023C1ED92748><class '__main__.GfG'><bound method GfG.call of <__main__.GfG object at 0x0000023C1ED92748>>Vivek called with parameters 'arg'
结果: 传统的方法比getattr()花费的时间少,但是当需要使用默认值以防缺少属性时,getattr()是一个不错的选择。
应用: getattr()有许多应用程序,其中一些已经在缺少对象属性的情况下提到,在web开发中,一些表单属性是可选的。在机器学习功能收集的情况下也很有用,以防某些功能有时在数据收集中丢失。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END