7

私が書いてきたコードでは、python記述子プロトコルをより広範囲に使用し始めました。通常、デフォルトの python ルックアップ マジックを実行したいのですが、__get__メソッドの結果ではなく記述子オブジェクト自体を取得したい場合があります。記述子のタイプ、または記述子に格納されているアクセス状態などを知りたい。

以下のコードを書いて、正しい順序であると思われる名前空間をたどり、記述子であるかどうかに関係なく、生の属性を返します。これを行うための組み込み関数や標準ライブラリの何かが見つからないことに驚いています-そこにある必要があると思いますが、それに気づいていないか、適切な検索用語をグーグル検索していません。

Python ディストリビューションのどこかに、既にこれを行っている機能 (または同様のもの) はありますか?

ありがとう!

from inspect import isdatadescriptor

def namespaces(obj):
    obj_dict = None
    if hasattr(obj, '__dict__'):
        obj_dict = object.__getattribute__(obj, '__dict__')

    obj_class = type(obj)
    return obj_dict, [t.__dict__ for t in obj_class.__mro__]

def getattr_raw(obj, name):
    # get an attribute in the same resolution order one would normally,
    # but do not call __get__ on the attribute even if it has one
    obj_dict, class_dicts = namespaces(obj)

    # look for a data descriptor in class hierarchy; it takes priority over
    # the obj's dict if it exists
    for d in class_dicts:
        if name in d and isdatadescriptor(d[name]):
            return d[name]

    # look for the attribute in the object's dictionary
    if obj_dict and name in obj_dict:
        return obj_dict[name]

    # look for the attribute anywhere in the class hierarchy
    for d in class_dicts:
        if name in d:
            return d[name]

    raise AttributeError

2009 年 10 月 28 日水曜日を編集。

Denis の答えは、記述子オブジェクト自体を取得するために記述子クラスで使用する規則を教えてくれました。しかし、私は記述子クラスのクラス階層全体を持っていたので、すべて __get__の関数をボイラープレートで始めたくありませんでした

def __get__(self, instance, instance_type):
    if instance is None: 
        return self
    ...

これを回避するために、記述子クラス ツリーのルートを次のものから継承させました。

def decorate_get(original_get):
    def decorated_get(self, instance, instance_type):
        if instance is None:
            return self
        return original_get(self, instance, instance_type)
    return decorated_get

class InstanceOnlyDescriptor(object):
    """All __get__ functions are automatically wrapped with a decorator which
    causes them to only be applied to instances. If __get__ is called on a 
    class, the decorator returns the descriptor itself, and the decorated
    __get__ is not called.
    """
    class __metaclass__(type):
        def __new__(cls, name, bases, attrs):
            if '__get__' in attrs:
                attrs['__get__'] = decorate_get(attrs['__get__'])
            return type.__new__(cls, name, bases, attrs)
4

4 に答える 4

13

ほとんどの記述子は、インスタンス属性としてのみアクセスされた場合に機能します。したがって、クラスにアクセスしたときにそれ自体を返すと便利です。

class FixedValueProperty(object):
    def __init__(self, value):
        self.value = value
    def __get__(self, inst, cls):
        if inst is None:
            return self
        return self.value

これにより、記述子自体を取得できます。

>>> class C(object):
...     prop = FixedValueProperty('abc')
... 
>>> o = C()
>>> o.prop
'abc'
>>> C.prop
<__main__.FixedValueProperty object at 0xb7eb290c>
>>> C.prop.value
'abc'
>>> type(o).prop.value
'abc'

これは(ほとんどの?)組み込み記述子でも機能することに注意してください。

>>> class C(object):
...     @property
...     def prop(self):
...         return 'abc'
... 
>>> C.prop
<property object at 0xb7eb0b6c>
>>> C.prop.fget
<function prop at 0xb7ea36f4>

記述子へのアクセスは、サブクラスで拡張する必要がある場合に役立ちますが、これを行うためのより良い方法があります。

于 2009-10-27T10:27:14.460 に答える
3

ライブラリは、inspect記述子マジックなしで属性を取得する関数を提供します: inspect.getattr_static.

ドキュメント: https://docs.python.org/3/library/inspect.html#fetching-attributes-statically

(これは古い質問ですが、これを行う方法を思い出そうとすると何度も出くわすので、もう一度見つけられるようにこの回答を投稿しています!)

于 2017-06-09T03:49:57.500 に答える
0

上記の方法

class FixedValueProperty(object):
    def __init__(self, value):
        self.value = value
    def __get__(self, inst, cls):
        if inst is None:
            return self
        return self.value

プロパティのコードを制御する場合はいつでも優れた方法ですが、プロパティが他の誰かによって制御されるライブラリの一部である場合など、別のアプローチが役立つ場合があります。この代替アプローチは、オブジェクト マッピングの実装、質問で説明されている名前空間のウォーク、または他の特殊なライブラリなど、他の状況でも役立ちます。

単純なプロパティを持つクラスを考えてみましょう:

class ClassWithProp:

    @property
    def value(self):
        return 3
>>>test=ClassWithProp()
>>>test.value
3
>>>test.__class__.__dict__.['value']
<property object at 0x00000216A39D0778>

コンテナー オブジェクト クラスdictからアクセスすると、「記述子マジック」がバイパスされます。プロパティを新しいクラス変数に割り当てると、「記述子マジック」を使用して元のプロパティと同じように動作しますが、インスタンス変数に割り当てると、プロパティは通常のオブジェクトとして動作し、「記述子マジック」もバイパスします。

>>> test.__class__.classvar =  test.__class__.__dict__['value']
>>> test.classvar
3
>>> test.instvar = test.__class__.__dict__['value']
>>> test.instvar
<property object at 0x00000216A39D0778>
于 2016-01-25T04:42:52.353 に答える