如何在 Python 中知道对象是否具有属性 [英] How to know if an object has an attribute in Python

查看:34
本文介绍了如何在 Python 中知道对象是否具有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中是否有一种方法可以确定对象是否具有某个属性?例如:

<预><代码>>>>a = SomeClass()>>>a.someProperty = 值>>>a.财产回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: SomeClass 实例没有属性property"

在使用之前如何判断a是否具有property属性?

解决方案

尝试 <代码>hasattr():

if hasattr(a, 'property'):a.财产

请参阅下面的 zweiterlinde 的回答,他提供了关于请求宽恕的好建议!一个非常pythonic的方法!

python 中的一般做法是,如果属性可能大部分时间都在那里,只需调用它并让异常传播,或者用 try/except 块捕获它.这可能比 hasattr 更快.如果大部分时间该属性可能不存在,或者您不确定,使用 hasattr 可能比反复陷入异常块要快.

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'

How can you tell if a has the attribute property before using it?

解决方案

Try hasattr():

if hasattr(a, 'property'):
    a.property

See zweiterlinde's answer below, who offers good advice about asking forgiveness! A very pythonic approach!

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 中知道对象是否具有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆