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?

3
  • 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. Commented Sep 13, 2012 at 10:05
  • Partial dupe of Accessing dict keys like an attribute in Python? Commented Sep 13, 2012 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. Commented Sep 13, 2012 at 10:08

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Does the dict class have any important attributes that this might obscure?
__getattr__ is only consulted for attributes not found otherwise; methods on the dict object trump keys with the same name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.