Search code examples
pythongetattrsetattr

__setattr__ only for names not found in the object's attributes`?


I want to use __setattr__ only when the attribute was not found in the object's attributes, like __getattr__.

Do I really have to use try-except?

def __setattr__(self, name, value):
    try:
        setattr(super(Clazz, self), name, value)
    except AttributeError:
        # implement *my* __setattr__
        pass

Solution

  • You can use hasattr():

    def __setattr__(self, name, value):
        if hasattr(super(Clazz, self), name):
            setattr(super(Clazz, self), name, value)
        else:
            # implement *my* __setattr__
            pass