Python hasattr() function is used to test if the specified object has the given attribute or not. This function returns a boolean value.
Python hasattr()函数用于测试指定的对象是否具有给定的属性。 该函数返回一个布尔值。
Python hasattr() (Python hasattr())
Python hasattr() function syntax is:
Python hasattr()函数语法为:
hasattr(object, name)
object
can be any object whose attribute will be checked.
object
可以是将检查其属性的任何对象。
name
should be string and name of the attribute to be checked.
name
应该是字符串,要检查的属性的名称。
Internally this function calls getattr(object, name) and returns True
. If AttributeError
is thrown by getattr() function call, then False
is returned. Otherwise, True
is returned.
在内部,此函数调用getattr(object,name)并返回True
。 如果getattr()函数调用引发AttributeError
,则返回False
。 否则,返回True
。
Python hasattr()示例 (Python hasattr() example)
Let’s look at an example of hasattr() function.
让我们看一个hasattr()函数的例子。
class Employee:
id = 0
name = ''
def __init__(self, i, n):
self.id = i
self.name = n
d = Employee(10, 'Pankaj')
if hasattr(d, 'name'):
print(getattr(d, 'name'))
Output: Pankaj
输出: Pankaj
Python hasattr()与 (Python hasattr() vs in)
The benefit of hasattr() function is visible when the attribute value is determined dynamically, such as getting it from user input. We can’t do the same thing with x in object
because of dynamic nature.
动态确定属性值(例如从用户输入获取属性值)时,可以看到hasattr()函数的好处。 由于动态特性,我们无法对x in object
做相同的事情。
Let’s look at another example where we will ask the user to enter the attribute value, then use hasattr() to check if it exists or not and proceed accordingly.
让我们看另一个示例,在该示例中,我们将要求用户输入属性值,然后使用hasattr()检查该属性值是否存在,然后进行相应处理。
d = Employee(10, 'Pankaj')
attr = input('\nPlease enter Employee attribute to get details:\n')
if hasattr(d, attr):
print(attr, '=', getattr(d, attr))
else:
print('invalid employee attribute')
Output:
输出:
Please enter Employee attribute to get details:
id
id = 10
# next iteration with invalid user input
Please enter Employee attribute to get details:
i
invalid employee attribute
摘要 (Summary)
Python hasattr() is a utility function to check if the attribute is present or not for the object before we try to use it in our program. We can easily implement this function or use try-expect to have this logic in our program, but using this function is recommended to have a clean code.
Python hasattr()是一个实用程序函数,可在我们尝试在程序中使用它之前检查对象的属性是否存在。 我们可以轻松地实现此功能,也可以使用try-expect在我们的程序中使用此逻辑,但是建议使用此功能以使用干净的代码。
Reference: Official Documentation
参考: 官方文档