python hasattr_Python hasattr()用法及代码示例

hasattr()是Python中的内置实用程序函数,已在许多day-to-day编程应用程序中使用。

它的主要任务是检查对象是否具有给定的命名属性,如果存在则返回true,否则返回false。

语法:hasattr(obj,key)

参数:

obj:必须检查其属性的对象。

key:需要检查的属性。

返回:如果属性存在,则返回True,否则返回False。

代码1:演示hasattr()的工作

# Python code to demonstrate

# working of hasattr()

# declaring class

class GfG:

name = "GeeksforGeeks"

age = 24

# initializing object

obj = GfG()

# using hasattr() to check name

print ("Does name exist ? " + str(hasattr(obj, 'name')))

# using hasattr() to check motto

print ("Does motto exist ? " + str(hasattr(obj, 'motto')))

输出:

Does name exist ? True

Does motto exist ? False

代码#2:性能分析

# Python code to demonstrate

# performance analysis of hasattr()

import time

# declaring class

class GfG:

name = "GeeksforGeeks"

age = 24

# initializing object

obj = GfG()

# use of hasattr to check motto

start_hasattr = time.time()

if(hasattr(obj, 'motto')):

print ("Motto is there")

else :

print ("No Motto")

print ("Time to execute hasattr:" + str(time.time() - start_hasattr))

# use of try/except to check motto

start_try = time.time()

try :

print (obj.motto)

print ("Motto is there")

except AttributeError:

print ("No Motto")

print ("Time to execute try:" + str(time.time() - start_try))

输出:

No Motto

Time to execute hasattr:5.245208740234375e-06

No Motto

Time to execute try:2.6226043701171875e-06

结果:常规的try /except比hasattr()花费的时间更少,但是对于代码的可读性而言,hasattr()始终是一个更好的选择。

应用范围:此功能可用于检查按键,以免在访问缺少的按键时产生不必要的错误。有时使用hasattr()链接来避免输入一个相关属性(如果不存在其他属性)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值