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 = 0name = ''def __init__(self, i, n):self.id = iself.name = nd = 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

Python hasattr()相关推荐

  1. Python eval()函数的使用

    Python eval()函数的使用 文章目录 一.官网给出的定义 1.eval() 方法的语法: 二.eval的作用 1.计算字符串中有效的表达式,并返回结果 2.将字符串转成相应的对象(如list ...

  2. Python xrange()函数

    Python xrange() function is used to generate a sequence of integers. This function is part of Python ...

  3. Python ord(),chr()函数

    Python ord() and chr() are built-in functions. They are used to convert a character to an int and vi ...

  4. Python bytearray()

    Python bytearray() function returns a bytearray object that contains the array of bytes from the inp ...

  5. Python complex()

    Python complex() function is used to create complex numbers. It's a built-in function that returns a ...

  6. Python Frozenset()

    Python frozenset is an unordered collection of distinct hashable objects. Frozenset is an immutable ...

  7. Python strftime()

    Python strftime() function is present in datetime and time modules to create a string representation ...

  8. Python raw_input()

    Good day, learners. In our previous tutorial we learned about Python SimpleHTTPServer. In this tutor ...

  9. Python sorted()函数

    Python sorted() function returns a sorted list from the items in the iterable. Python sorted()函数从ite ...

最新文章

  1. 可以用JAVA编程的物联网开发板,了解一下?
  2. 话里话外:浅谈国企绩效考核问题(二)
  3. 带有WildFly Swarm的远程JMS
  4. linux批量替换文件夹中所有文件内容
  5. php 实现资料下载功能,学习猿地-php如何实现下载功能
  6. 巧妙实现表格奇偶行换色
  7. IT不是技术,IT是一个世界
  8. 安装黑群晖找不到局域网电脑_黑群晖洗白太复杂?我用蒲公英P5轻松实现
  9. PR(Adobe Premiere Pro)软件基础知识
  10. 2020计算机一级必背知识点,2020高考理综必背知识点
  11. Word 2007书籍排版完全手册
  12. python脚本检查文件内容
  13. 天翼云服务器怎么重装系统,天翼云操作系统介绍
  14. 通过搜狗蜘蛛池,让网站收录排名提升
  15. 概率 (菜鸡 dalao轻喷
  16. 安卓开发实现俄罗斯方块游戏
  17. C语言谭浩强第三版第十二章例题及课后题:位运算
  18. 网站后缀名html,网页后缀名有哪些
  19. 微信设置水滴昵称,个性很漂亮,快试试!
  20. java jsp小例题_JSP 相关试题(一)

热门文章

  1. hadoop-2.6下载地址
  2. 免费在线!!!多PDF合成一个PDF
  3. VSC/SMC(十六)——自适应鲁棒滑模控制
  4. 在线配资的诀窍是什么?
  5. 小A是大四的学生,还有半年就要毕业了
  6. 学了3,4年,终于明白了高斯白噪声的那些东西。
  7. 深入理解iOS APP启动过程
  8. 构造方法以及构造方法的重载
  9. 华为ENSP网络设备配置实战2(较为复杂的ospf)
  10. 百度地图、高德地图等商用5w/年怎么搞