在Python中检查数据描述符属性

4
我尝试使用数据描述符为类的属性提供自定义的get/set功能。我希望能够在运行时检查类并获取该类上的数据描述符列表,甚至可能确定描述符的类型。
问题在于,当我使用inspect.getmembers获取成员时,我的数据描述符属性被解析了(它们的__get__方法已经被调用,并且该结果被设置为对象的值)。
我正在使用来自http://docs.python.org/2/howto/descriptor.html的示例。
import inspect

class RevealAccess(object):
    """A data descriptor that sets and returns values
       normally and prints a message logging their access.
    """

    def __init__(self, initval=None, name='var'):
        self.val = initval
        self.name = name

    def __get__(self, obj, objtype):
        print 'Retrieving', self.name
        return self.val

    def __set__(self, obj, val):
        print 'Updating', self.name
        self.val = val


class MyClass(object):
    x = RevealAccess(10, 'var "x"')
    y = 5

if __name__ == '__main__':
    for x in inspect.getmembers(MyClass, inspect.isdatadescriptor):
        print x

当我运行此代码时,会出现以下信息:
Retrieving var "x"
('__weakref__', <attribute '__weakref__' of 'MyClass' objects>)

What I expect is more like:

('x', <attribute 'x' of 'MyClass' objects>)
('__weakref__', <attribute '__weakref__' of 'MyClass' objects>)

我知道我缺少什么,但就是想不起来。非常感谢您的帮助。

1个回答

3
要获取描述符本身,您可以查看__dict__类:
MyClass.__dict__['x']

但更好的方式是修改getter方法:

def __get__(self, obj, objtype):
    print 'Retrieving', self.name
    if obj is None:  # accessed as class attribute
        return self  # return the descriptor itself
    else:  # accessed as instance attribute
        return self.val  # return a value

这将得到:

Retrieving var "x"
('__weakref__', <attribute '__weakref__' of 'MyClass' objects>)
('x', <__main__.RevealAccess object at 0x7f32ef989890>)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接