📜  Python hasattr() 方法

📅  最后修改于: 2022-05-13 01:54:49.624000             🧑  作者: Mango

Python hasattr() 方法

Python hasattr()函数是一个内置的实用函数,用于检查对象是否具有给定的命名属性,如果存在则返回 true,否则返回 false。

hasattr() 方法的语法是:

Python hasattr() 方法示例:

示例 1: 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')))


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))


输出:

Does name exist ? True
Does 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 Motto
Time to execute hasattr : 5.245208740234375e-06
No Motto
Time to execute try : 2.6226043701171875e-06

结果:传统的 try/except 比 hasattr() 花费的时间更少,但是为了代码的可读性,hasattr() 总是更好的选择。

应用:此函数可用于检查密钥,以避免在访问缺少密钥的情况下出现不必要的错误。 hasattr() 的链接有时用于避免一个相关属性的条目,如果另一个相关属性不存在。