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

私が期待するのは、次のようなものです。

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

指を置くことができない何かが欠けていることを私は知っています。どんな助けでも感謝します。

4

1 に答える 1

3

記述子自体を取得するには、 class を調べます__dict__

MyClass.__dict__['x']

しかし、より良い方法はゲッターを変更することです:

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>)
于 2013-06-28T16:04:24.040 に答える