Question

I have been reading about overriding getattr and setattr and I can't figure out if I need the overriding assignments if I use self.__dict__ = self in the constructor.

Once I make an instance of the class

a = OPT(foo='bar')

a.foo and a['foo'] work with and without the __getattr__ and __setattr__ declaration.

Can someone explain if I need both. If I do, why? Thanks!

class OPT(dict):
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__

    def __init__(self, *args, **kwargs):
        super(OPT, self).__init__(*args, **kwargs)
        self.__dict__ = self

No correct solution

OTHER TIPS

You override getattr and setattr when you want to do something extra when the class user gets or sets an attribute. For example:

1) you might avoid raising an exception when user manipulates an invalid attribute, so you just return None for an unknown attribute.

2) attribute manipulations are actually forwarded/delegated, so the valid attributes are not known in advance e.g. a class that represents a database row and the user manipulates columns as attributes. I need to run-time check if the given attribute name matches column name, and perhaps I'd like to forgive upper-case/lower-case differences etc.

Another thing, containment is sometimes preferred to subclassing. Instead of inheriting from a dict, you could create a class that contains a dict.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top