Is there any trick to "overload the dot operator"?

In object1's class definition,

def __getattr__(self, key):
    return self.get(key)

Any attempt to resolve a property, method, or field name that doesn't actually exist on the object itself will be passed to __getattr__.

If you don't have access to the class definition, i.e. it's something like a dictionary, wrap it in a class. For a dictionary, you could do something like:

class DictWrapper(object):
    def __init__(self, d):
        self.d = d
    def __getattr__(self, key):
        return self.d[key]

Note that a KeyError will be raised if the key is invalid; the convention, however, is to raise an AttributeError (thanks, S. Lott!). You can re-raise the KeyError as an AttributeError like so, if necessary:

try:
    return self.get(key)
except KeyError as e:
    raise AttributeError(e)

Also remember that if the objects you are returning from __getattr__ are also, for example, dictionaries, you'll need to wrap them too.


Wrap the structure in an object with adefined __getattr__() method. If you have any control over the structure you can define its own __getattr___(). Getattr does just what you want - "catches" missing attributes and possibly returns some value.

Tags:

Python

Json