检查python中是否有某个属性或装饰器

时间:2013-04-23 12:57:28

标签: python decorator magic-methods

我想包装遗留代码库的模型类。模型类有一个字典,其中包含元信息和访问该字典以及属性的属性。我想使用an_object[some_key]使用__getitem__语法统一对元信息,属性和属性的访问。问题是,某些属性有getter但不是setter。因此,尝试检查属性是否存在(通过hasattr)返回True,但随后设置该属性失败,因为没有定义属性。

如何确定我是否可以安全地设置属性,或者它是否是我需要在元字典中设置的属性?

1 个答案:

答案 0 :(得分:3)

您可以通过查看类中的相同属性来检测某些内容是否为属性:

class_attribute = getattr(type(instance), some_key, None)
if isinstance(class_attribute, property):
    # this is a property
    if class_attribute.fset is None:
        print "Read-only"

您还可以测试.fget.fdel以测试该属性是否分别具有getter和deleter。

但是,您始终可以捕获AttributeError异常来处理缺少的setter:

>>> class Foo(object):
...     @property
...     def bar(self):
...         return 'spam'
... 
>>> f = Foo()
>>> class_attribute = getattr(type(f), 'bar', None)
>>> isinstance(class_attribute, property)
True
>>> class_attribute.fget
<function bar at 0x10aa8c668>
>>> class_attribute.fset is None
True
>>> try:
...     f.bar = 'baz'
... except AttributeError:
...     print 'Read-only'
... 
Read-only
相关问题