2

Say we have a class:

class Foo (object):
...     def __init__(self,d):
...         self.d=d
...     def return_d(self):
...         return self.d

... and a dict:

d={'k1':1,'k2':2}

... and an instance:

inst=Foo(d)

Is there a way to dynamically add attributes to return_d so:

inst.return_d.k1 would return 1?

4

1 に答える 1

9

return_d属性またはプロパティとして宣言し、辞書キーの属性アクセスを許可する dict のようなオブジェクトを返すという2 つのことを行う必要があります。次のように動作します。

class AttributeDict(dict): 
    __getattr__ = dict.__getitem__

class Foo (object):
    def __init__(self,d):
        self.d=d

    @property
    def return_d(self):
        return AttributeDict(self.d)

短いデモ:

>>> foo = Foo({'k1':1,'k2':2})
>>> foo.return_d.k1
1

propertyデコレータはメソッドを属性に変換し、フック__getattr__クラスが属性アクセス (演算子)AttributeDictを介して辞書キーを検索できるようにします。.

于 2012-09-13T10:09:23.483 に答える