Python hasattr()

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在我们的程序中使用此逻辑,但是建议使用此功能以使用干净的代码。

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/22884/python-hasattr

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值