Python hasattr()函数 是一个内置的实用程序函数,用于检查对象是否具有给定的命名属性,如果存在,则返回true,否则返回false。
null
hasattr()方法的语法是:
语法: hasattr(obj,钥匙)
参数:
- obj: 必须检查其属性的对象。
- 关键: 需要检查的属性。
返回: 如果属性存在,则返回True,否则返回False。
Python hasattr()方法示例:
例1:W hasattr()的定义
Python3
# 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 ? TrueDoes motto exist ? False
示例2:hasattr()方法和try语句之间的性能分析
Python3
# 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 MottoTime to execute hasattr : 5.245208740234375e-06No MottoTime to execute try : 2.6226043701171875e-06
结果: 传统的try/except比hasattr()花费的时间更少,但对于代码的可读性,hasattr()总是一个更好的选择。
应用: 此功能可用于检查密钥,以避免在访问缺少密钥的情况下出现不必要的错误。hasattr()的链接有时用于避免在一个相关属性不存在时输入另一个相关属性。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END