如何检查一个对象是否具有属性?

发布于 2024-07-14 16:22:48 字数 316 浏览 10 评论 0原文

如何检查一个对象是否具有某些属性? 例如:

>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'

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

How do I check if an object has some attribute? For example:

>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'

How do I tell if a has the attribute property before using it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

白况 2024-07-21 16:22:49

根据情况你可以使用isinstance检查你拥有什么类型的对象,然后使用相应的属性。 随着 Python 2.6/3.0 中引入抽象基类,这种方法也变得更加强大(基本上 ABC 允许更复杂的鸭子类型)。

一种有用的情况是,如果两个不同的对象具有名称相同但含义不同的属性。 仅使用 hasattr 可能会导致奇怪的错误。

一个很好的例子是迭代器和可迭代之间的区别(请参阅

但是,我同意在大多数情况下 hasattr 方法(在其他答案中描述)是最合适的解决方案。

Depending on the situation you can check with isinstance what kind of object you have, and then use the corresponding attributes. With the introduction of abstract base classes in Python 2.6/3.0 this approach has also become much more powerful (basically ABCs allow for a more sophisticated way of duck typing).

One situation were this is useful would be if two different objects have an attribute with the same name, but with different meaning. Using only hasattr might then lead to strange errors.

One nice example is the distinction between iterators and iterables (see this question). The __iter__ methods in an iterator and an iterable have the same name but are semantically quite different! So hasattr is useless, but isinstance together with ABC's provides a clean solution.

However, I agree that in most situations the hasattr approach (described in other answers) is the most appropriate solution.

绮烟 2024-07-21 16:22:49

希望您期待 hasattr(),但尽量避免 hasattr(),而更喜欢 getattr()。 getattr() 比 hasattr() 更快

使用 hasattr():

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

同样,我使用 getattr 来获取属性,如果没有属性,则不返回任何属性

   property = getattr(a,"property",None)
    if property:
        print property

Hope you expecting hasattr(), but try to avoid hasattr() and please prefer getattr(). getattr() is faster than hasattr()

using hasattr():

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

same here i am using getattr to get property if there is no property it return none

   property = getattr(a,"property",None)
    if property:
        print property
也只是曾经 2024-07-21 16:22:49

您可以使用 hasattr() 来检查Python 中对象或类是否具有属性。

例如,有 Person,如下所示:

class Person:
    greeting = "Hello"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def test(self):
        print("Test")

然后,您可以使用 hasattr() for object 如下所示:

obj = Person("John", 27)
obj.gender = "Male"
print("greeting:", hasattr(obj, 'greeting'))
print("name:", hasattr(obj, 'name'))
print("age:", hasattr(obj, 'age'))
print("gender:", hasattr(obj, 'gender'))
print("test:", hasattr(obj, 'test'))
print("__init__:", hasattr(obj, '__init__'))
print("__str__:", hasattr(obj, '__str__'))
print("__module__:", hasattr(obj, '__module__'))

输出:

greeting: True
name: True
age: True
gender: True
test: True
__init__: True
__str__: True
__module__: True

并且,您还可以使用 hasattr() 直接用于类名

print("greeting:", hasattr(Person, 'greeting'))
print("name:", hasattr(Person, 'name'))
print("age:", hasattr(Person, 'age'))
print("gender:", hasattr(Person, 'gender'))
print("test:", hasattr(Person, 'test'))
print("__init__:", hasattr(Person, '__init__'))
print("__str__:", hasattr(Person, '__str__'))
print("__module__:", hasattr(Person, '__module__'))

输出:

greeting: True
name: False
age: False
gender: False
test: True
__init__: True
__str__: True
__module__: True

You can use hasattr() to check if object or class has an attribute in Python.

For example, there is Person class as shown below:

class Person:
    greeting = "Hello"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def test(self):
        print("Test")

Then, you can use hasattr() for object as shown below:

obj = Person("John", 27)
obj.gender = "Male"
print("greeting:", hasattr(obj, 'greeting'))
print("name:", hasattr(obj, 'name'))
print("age:", hasattr(obj, 'age'))
print("gender:", hasattr(obj, 'gender'))
print("test:", hasattr(obj, 'test'))
print("__init__:", hasattr(obj, '__init__'))
print("__str__:", hasattr(obj, '__str__'))
print("__module__:", hasattr(obj, '__module__'))

Output:

greeting: True
name: True
age: True
gender: True
test: True
__init__: True
__str__: True
__module__: True

And, you can also use hasattr() directly for class name as shown below:

print("greeting:", hasattr(Person, 'greeting'))
print("name:", hasattr(Person, 'name'))
print("age:", hasattr(Person, 'age'))
print("gender:", hasattr(Person, 'gender'))
print("test:", hasattr(Person, 'test'))
print("__init__:", hasattr(Person, '__init__'))
print("__str__:", hasattr(Person, '__str__'))
print("__module__:", hasattr(Person, '__module__'))

Output:

greeting: True
name: False
age: False
gender: False
test: True
__init__: True
__str__: True
__module__: True
梦归所梦 2024-07-21 16:22:49

这非常简单,只需使用 dir(object)

这将返回对象的每个可用函数和属性的列表。

This is super simple, just use dir(object)

This will return a list of every available function and attribute of the object.

瘫痪情歌 2024-07-21 16:22:49

您可以使用 hasattr 内置方法检查 object 是否包含属性。

例如,如果您的对象是 a 并且您想要检查属性 stuff

>>> class a:
...     stuff = "something"
... 
>>> hasattr(a,'stuff')
True
>>> hasattr(a,'other_stuff')
False

方法签名本身是 hasattr(object, name) -> bool 表示如果 object 具有传递给 hasattr 中第二个参数的属性,则它会给出布尔值 True 或 False 根据对象中是否存在 name 属性。

You can check whether object contains attribute by using hasattr builtin method.

For an instance if your object is a and you want to check for attribute stuff

>>> class a:
...     stuff = "something"
... 
>>> hasattr(a,'stuff')
True
>>> hasattr(a,'other_stuff')
False

The method signature itself is hasattr(object, name) -> bool which mean if object has attribute which is passed to second argument in hasattr than it gives boolean True or False according to the presence of name attribute in object.

谁许谁一生繁华 2024-07-21 16:22:49

另一种可能的选择,但这取决于您的意思是否之前

undefined = object()

class Widget:

    def __init__(self):
        self.bar = 1

    def zoom(self):
        print("zoom!")

a = Widget()

bar = getattr(a, "bar", undefined)
if bar is not undefined:
    print("bar:%s" % (bar))

foo = getattr(a, "foo", undefined)
if foo is not undefined:
    print("foo:%s" % (foo))

zoom = getattr(a, "zoom", undefined)
if zoom is not undefined:
    zoom()

输出:

bar:1
zoom!

这甚至允许您检查无值属性。

但! 请务必小心,不要意外实例化并比较 undefined 多个位置,因为 is 在这种情况下永远不会起作用。

更新:

由于我在上一段中警告过,有多个从未匹配的未定义,我最近稍微修改了此模式:

undefined = NotImplemented

NotImplemented,而不是与 NotImplementedError 混淆,它是一个内置的:它半匹配 JS undefined 的意图,你可以在任何地方重用它的定义,并且它总是匹配。 缺点是它在布尔值中是“真实的”,并且在日志和堆栈跟踪中看起来很奇怪(但是当您知道它只出现在这种情况下时,您很快就会克服它)。

Another possible option, but it depends if what you mean by before:

undefined = object()

class Widget:

    def __init__(self):
        self.bar = 1

    def zoom(self):
        print("zoom!")

a = Widget()

bar = getattr(a, "bar", undefined)
if bar is not undefined:
    print("bar:%s" % (bar))

foo = getattr(a, "foo", undefined)
if foo is not undefined:
    print("foo:%s" % (foo))

zoom = getattr(a, "zoom", undefined)
if zoom is not undefined:
    zoom()

output:

bar:1
zoom!

This allows you to even check for None-valued attributes.

But! Be very careful you don't accidentally instantiate and compare undefined multiple places because the is will never work in that case.

Update:

because of what I was warning about in the above paragraph, having multiple undefineds that never match, I have recently slightly modified this pattern:

undefined = NotImplemented

NotImplemented, not to be confused with NotImplementedError, is a built-in: it semi-matches the intent of a JS undefined and you can reuse its definition everywhere and it will always match. The drawbacks is that it is "truthy" in booleans and it can look weird in logs and stack traces (but you quickly get over it when you know it only appears in this context).

我很坚强 2024-07-21 16:22:48

尝试hasattr()

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

参见zweiterlinde 的回答如下,他提供了有关请求宽恕的好建议! 一个非常Pythonic的方法!

python 中的一般做法是,如果该属性在大多数情况下可能都存在,则只需调用它并让异常传播,或者使用 try/ except 块捕获它。 这可能会比 hasattr 更快。 如果该属性在大多数情况下可能不存在,或者您不确定,那么使用 hasattr 可能比反复陷入异常块更快。

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.

一场信仰旅途 2024-07-21 16:22:48

正如 贾瑞特·哈迪 回答说,hasattr 就可以了。 不过,我想补充一点,Python 社区中的许多人建议采用“请求宽恕比请求许可更容易”(EAFP) 的策略,而不是“三思而后行”(LBYL)。 请参阅这些参考文献:

EAFP vs LBYL(回复:到目前为止有点失望)
EAFP 与 LBYL @Code Like a Pythonista: Idiomatic Python

ie:

try:
    doStuff(a.property)
except AttributeError:
    otherStuff()

... 优先于:

if hasattr(a, 'property'):
    doStuff(a.property)
else:
    otherStuff()

As Jarret Hardie answered, hasattr will do the trick. I would like to add, though, that many in the Python community recommend a strategy of "easier to ask for forgiveness than permission" (EAFP) rather than "look before you leap" (LBYL). See these references:

EAFP vs LBYL (was Re: A little disappointed so far)
EAFP vs. LBYL @Code Like a Pythonista: Idiomatic Python

ie:

try:
    doStuff(a.property)
except AttributeError:
    otherStuff()

... is preferred to:

if hasattr(a, 'property'):
    doStuff(a.property)
else:
    otherStuff()
沫尐诺 2024-07-21 16:22:48

您可以使用 hasattr() 或 catch AttributeError,但如果您确实只想获得默认属性值(如果不存在),那么最好的选择就是使用 getattr()

getattr(a, 'property', 'default value')

You can use hasattr() or catch AttributeError, but if you really just want the value of the attribute with a default if it isn't there, the best option is just to use getattr():

getattr(a, 'property', 'default value')
烦人精 2024-07-21 16:22:48

我认为您正在寻找的是hasattr。 但是,如果您想检测 python 属性,我建议使用类似的方法 -

try:
    getattr(someObject, 'someProperty')         
except AttributeError:
    print "Doesn't exist"
else
    print "Exists"

这里的缺点是属性 __get__ 代码中的属性错误也会被捕获。

否则,请执行-

if hasattr(someObject, 'someProp'):
    #Access someProp/ set someProp
    pass

文档:http://docs.python.org/library/functions.html
警告:
我推荐的原因是 hasattr 不检测属性。
链接:
http://mail.python.org/pipermail/python -dev/2005-12月/058498.html

I think what you are looking for is hasattr. However, I'd recommend something like this if you want to detect python properties-

try:
    getattr(someObject, 'someProperty')         
except AttributeError:
    print "Doesn't exist"
else
    print "Exists"

The disadvantage here is that attribute errors in the properties __get__ code are also caught.

Otherwise, do-

if hasattr(someObject, 'someProp'):
    #Access someProp/ set someProp
    pass

Docs:http://docs.python.org/library/functions.html
Warning:
The reason for my recommendation is that hasattr doesn't detect properties.
Link:http://mail.python.org/pipermail/python-dev/2005-December/058498.html

隐诗 2024-07-21 16:22:48

根据 pydoc,hasattr(obj, prop) 只需调用 getattr(obj, prop) 并捕获异常。 因此,使用 try 语句包装属性访问并捕获 AttributeError 与事先使用 hasattr() 一样有效。

a = SomeClass()
try:
    return a.fake_prop
except AttributeError:
    return default_value

According to pydoc, hasattr(obj, prop) simply calls getattr(obj, prop) and catches exceptions. So, it is just as valid to wrap the attribute access with a try statement and catch AttributeError as it is to use hasattr() beforehand.

a = SomeClass()
try:
    return a.fake_prop
except AttributeError:
    return default_value
烟若柳尘 2024-07-21 16:22:48

我想建议避免这种情况:

try:
    doStuff(a.property)
except AttributeError:
    otherStuff()

用户@jpalecek提到过:如果doStuff()内部发生AttributeError,你就会迷失。

也许这种方法更好:

try:
    val = a.property
except AttributeError:
    otherStuff()
else:
    doStuff(val)

I would like to suggest avoid this:

try:
    doStuff(a.property)
except AttributeError:
    otherStuff()

The user @jpalecek mentioned it: If an AttributeError occurs inside doStuff(), you are lost.

Maybe this approach is better:

try:
    val = a.property
except AttributeError:
    otherStuff()
else:
    doStuff(val)
§普罗旺斯的薰衣草 2024-07-21 16:22:48

对于字典以外的对象:

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

对于字典,hasattr() 将不起作用。

许多人建议使用 has_key() 作为字典,但它已被贬值。
所以对于字典,你必须使用 has_attr()

if a.has_attr('property'):
    a['property']
 

或者你也可以使用

if 'property' in a:

For objects other than dictonary:

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

For dictionary, hasattr() will not work.

Many people are telling to use has_key() for dictionary, but it is depreciated.
So for dictionary, you have to use has_attr()

if a.has_attr('property'):
    a['property']
 

Or you can also use

if 'property' in a:
梦醒时光 2024-07-21 16:22:48

hasattr() 是正确的答案。 我想补充的是 hasattr() 可以很好地与 assert (避免不必要的 if 语句并使代码更具可读性):

assert hasattr(a, 'property'), 'object lacks property' 
print(a.property)

如果缺少该属性,程序将退出一个 AssertionError 并打印出提供的错误消息(在本例中是对象缺少属性)。

正如另一个关于SO的答案中所述:

断言应该用于测试不应该发生的情况。
目的是在程序状态损坏的情况下尽早崩溃。

通常情况下,当属性丢失时,assert 就非常合适。

hasattr() is the right answer. What I want to add is that hasattr() can be used well in conjunction with assert (to avoid unnecessary if statements and make the code more readable):

assert hasattr(a, 'property'), 'object lacks property' 
print(a.property)

In case that the property is missing, the program will exit with an AssertionError and printing out the provided error message (object lacks property in this case).

As stated in another answer on SO:

Asserts should be used to test conditions that should never happen.
The purpose is to crash early in the case of a corrupt program state.

Often this is the case when a property is missing and then assert is very appropriate.

献世佛 2024-07-21 16:22:48

编辑:这种方法有严重的局限性。 如果对象是一个可迭代对象,它应该可以工作。 请检查下面的评论。

如果您像我一样使用 Python 3.6 或更高版本,那么有一个方便的替代方法来检查对象是否具有特定属性:

if 'attr1' in obj1:
    print("attr1 = {}".format(obj1["attr1"]))

但是,我不确定现在哪种方法是最好的方法。 使用 hasattr()、使用 getattr() 或使用 in。 欢迎评论。

EDIT:This approach has serious limitation. It should work if the object is an iterable one. Please check the comments below.

If you are using Python 3.6 or higher like me there is a convenient alternative to check whether an object has a particular attribute:

if 'attr1' in obj1:
    print("attr1 = {}".format(obj1["attr1"]))

However, I'm not sure which is the best approach right now. using hasattr(), using getattr() or using in. Comments are welcome.

混浊又暗下来 2024-07-21 16:22:48

这是一个非常直观的方法:

if 'property' in dir(a):
    a.property

如果a是字典,则可以正常检查

if 'property' in a:
    a.property

Here's a very intuitive approach :

if 'property' in dir(a):
    a.property

If a is a dictionary, you can check normally

if 'property' in a:
    a.property
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文