【问题标题】:How to tell if a Python class member is decorated with `@property` [duplicate]如何判断 Python 类成员是否用`@property`装饰[重复]
【发布时间】:2021-08-19 01:38:29
【问题描述】:

我正在继承UUID,我试图弄清楚UUID.hex 是普通成员还是用@property 装饰的方法。我不得不查看源代码才能弄清楚,这让我想知道是否还有其他方法。

>>> import uuid
>>> x = uuid.UUID('0000180000001000800000805f9b34fb')
>>> print([attr for attr in dir(x) if callable(getattr(x, attr))])
['__class__', '__delattr__', '__dir__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__']
>>> print([attr for attr in dir(x) if not callable(getattr(x, attr))])
['__doc__', '__module__', '__slots__', '__weakref__', 'bytes', 'bytes_le', 'clock_seq', 'clock_seq_hi_variant', 'clock_seq_low', 'fields', 'hex', 'int', 'is_safe', 'node', 'time', 'time_hi_version', 'time_low', 'time_mid', 'urn', 'variant', 'version']

The source code 是:

    @property
    def hex(self):
        return '%032x' % self.int

这是一个用@property 装饰的方法。我有点期待hex 会显示为callable(),但事实并非如此。有什么方法可以通过检查类或对象来判断吗?

谢谢!

【问题讨论】:

标签: python


【解决方案1】:

Python 中的property 装饰器采用一个方法并将其包装在 上定义的属性中。然后,该类的实例足够聪明,可以在引用该属性时表现出不同的行为。

让我们建立一个简单的类,一个属性和一个字段,以及该类的一个实例,用于测试

class A:

    def __init__(self):
        self.my_field = "foo"

    @property
    def my_property(self):
        return "foo"

a = A()

然后,如果我们在 REPL 中检查这个类,我们会看到 a.my_fielda.my_property 都是 "foo"。更有趣的是,A.my_fieldAttributeErrorA.my_propertyproperty 对象(即 property 类的实例。这正是我们可以使用的

def is_property(class_, name):
    try:
        return isinstance(getattr(class_, name), property)
    except AttributeError:
        return False

如果类中不存在该名称,则返回False,因为它绝对不是属性。如果是,则检查它是否是property 类的实例。像这样称呼它

is_property(A, 'my_field')
is_property(A, 'my_property')

(注意我们使用的是类,而不是实例;字段名是字符串)

Try it online!

【讨论】:

  • 你的 is_property 函数可能只返回 isinstance(getattr(class_, name, False), property) ?
猜你喜欢
  • 2011-04-27
  • 2013-05-12
  • 2013-10-26
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-24
  • 1970-01-01
相关资源
最近更新 更多