确定一个类属性是属性?

时间:2014-10-23 09:13:26

标签: python descriptor

有没有办法确定类属性是Property__get__还是__set__? 方法在 Determine if given class attribute is a property or not, Python object看起来只适用于property装饰器,这在我的情况下无效。

class Property(object):
    _value = None
    def __get__(self, instance, owner):
        return self._value 
    def __set__(self, instance, value):
        self._value = value * 2


class A(object):
    b = Property()

>>> a = A()
>>> type(A.p)
<type 'NoneType'>
>>> type(a.p)
<type 'NoneType'>

1 个答案:

答案 0 :(得分:1)

您的描述符返回None,因为它为类调用 instance属性在调用None时设置为__get__那个场景)。

你需要在没有调用描述符协议的情况下检索它,到达类__dict__属性是最直接的路径:

A.__dict__['p']

有关如何以及何时调用描述符的详细信息,请参阅Python Descriptor HOWTO

或者,在property对象执行时执行,并在self设置为instance时返回None(因此在类上访问时):

class Property(object):
    _value = None
    def __get__(self, instance, owner):
        if instance is None:
            return self
        return self._value 
    def __set__(self, instance, value):
        self._value = value * 2

另见How does the @property decorator work?

演示:

>>> class Property(object):
...     def __get__(self, instance, owner):
...         return self._value 
...     def __set__(self, instance, value):
...         self._value = value * 2
... 
>>> class A(object):
...     b = Property()
... 
>>> A.__dict__['b']
<__main__.Property object at 0x103097910>
>>> type(A.__dict__['b'])
<class '__main__.Property'>
>>> class Property(object):
...     _value = None
...     def __get__(self, instance, owner):
...         if instance is None:
...             return self
...         return self._value 
...     def __set__(self, instance, value):
...         self._value = value * 2
... 
>>> class A(object):
...     b = Property()
... 
>>> A.b
<__main__.Property object at 0x10413d810>