Home > Software design >  Which magic method does hasattr call?
Which magic method does hasattr call?

Time:08-02

Which magic method method does hasattr call?

getattr(__o, name) can also be called as __o.__getattr__(name)

setattr(__o, name) can also be called as __o.__setattr__(name)

But what is the equivalent for hasattr?

I know the associated magic method for the in keyword is __contains__.

CodePudding user response:

There is no specific dunder method for hasattr(). It's essentially equivalent to:

def hasattr(object, name):
    try:
        getattr(object, name)
        return True
    except AttributeError:
        return False

So it's dependent on the same dunder methods used by getattr().

CodePudding user response:

The documentation for hasattr specifically states that

This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.

That means that the __getattr__ and __getattribute__ are the dunders you are most concerned about.

  • Related