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开发中)很少提及。在机器学习功能集合的情况下,如果某些功能有时在数据收集中丢失,也很有用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值