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?

root
  • 76,608
  • 25
  • 108
  • 120
  • Why won't `inst.return_d()['k1']` do? The `.` operator does an attribute lookup, so whatever `return_d` returns, should support attribute lookups, perhaps via the `__getattr__` hook. Note that you expect `return_d` to be an attribute, but you defined it as a method, so the example you state would not work on that account alone. – Martijn Pieters Sep 13 '12 at 10:05
  • Partial dupe of [Accessing dict keys like an attribute in Python?](http://stackoverflow.com/q/4984647) – Martijn Pieters Sep 13 '12 at 10:06
  • @Pieter: it would do. It is a silly example, just trying to lear more about classes and what I can and cannot do. – root Sep 13 '12 at 10:08

1 Answers1

9

You'd need to do two things: declare return_d as an attribute or property, and return a dict-like object that allows attribute access for dictionary keys. The following would work:

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)

Short demo:

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

The property decorator turns methods into attributes, and the __getattr__ hook allows the AttributeDict class to look up dict keys via attribute access (the . operator).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343