How to know if an object has an attribute in Python(如何知道一个对象是否在 Python 中有一个属性)
问题描述
在 Python 中有没有办法确定一个对象是否具有某些属性?例如:
Is there a way in Python to determine if an object has some attribute? For example:
>>> a = SomeClass()
>>> a.someProperty = value
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
如何判断a
在使用前是否有属性property
?
How can you tell if a
has the attribute property
before using it?
推荐答案
试试<代码>hasattr():
if hasattr(a, 'property'):
a.property
请参阅下面的 zweiterlinde 的回答,他提供了关于请求宽恕的好建议!一个非常pythonic的方法!
See zweiterlinde's answer below, who offers good advice about asking forgiveness! A very pythonic approach!
python 中的一般做法是,如果该属性可能大部分时间都存在,则只需调用它并让异常传播,或者使用 try/except 块捕获它.这可能比 hasattr
更快.如果该属性可能大部分时间都不存在,或者您不确定,使用 hasattr
可能会比反复陷入异常块更快.
The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than hasattr
. If the property is likely to not be there most of the time, or you're not sure, using hasattr
will probably be faster than repeatedly falling into an exception block.
这篇关于如何知道一个对象是否在 Python 中有一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何知道一个对象是否在 Python 中有一个属性


基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01