简体   繁体   English

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

[英]Inspecting data descriptor attributes in python

I'm attempting to use a data descriptor to provide some custom get/set functionality to attributes of a class. 我正在尝试使用数据描述符为类的属性提供一些自定义的get / set功能。 I'd like to be able to inspect the class at runtime and get a list of data descriptors on that class, and maybe even determine what the type of the descriptor is. 我希望能够在运行时检查类并获取该类的数据描述符列表,甚至可以确定描述符的类型。

The problem is that when I look at the members I get using inspect.getmembers my data descriptor attributes are resolved (their __get__ method is already called and that result is set as the value of the object). 问题是,当我查看使用inspect.getmembers的成员时,我的数据描述符属性被解析(它们的__get__方法已被调用,结果被设置为对象的值)。

I'm using the example from: http://docs.python.org/2/howto/descriptor.html 我正在使用以下示例: 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

When I run this, I get: 当我运行这个时,我得到:

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>)

I know I'm missing something I just can't put my finger on it. 我知道我错过了一些我不能把手指放在上面的东西。 Any help appreciated. 任何帮助赞赏。

To get the descriptor itself, you can look into class __dict__ : 要获取描述符本身,您可以查看类__dict__

MyClass.__dict__['x']

But the better way is to modify the getter: 但更好的方法是修改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

Which gives: 这使:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM