有没有办法确定类属性是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'>
答案 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>