Understanding the difference between __getattr__ and __getattribute__

后端 未结 4 842
深忆病人
深忆病人 2020-11-29 14:44

I am trying to understand the difference between __getattr__ and __getattribute__, however, I am failing at it.

The answer to the Stack Ove

4条回答
  •  再見小時候
    2020-11-29 15:05

    Some basics first.

    With objects, you need to deal with its attributes. Ordinarily we do instance.attribute. Sometimes we need more control (when we do not know the name of the attribute in advance).

    For example, instance.attribute would become getattr(instance, attribute_name). Using this model, we can get the attribute by supplying the attribute_name as a string.

    Use of __getattr__

    You can also tell a class how to deal with attributes which it doesn't explicitly manage and do that via __getattr__ method.

    Python will call this method whenever you request an attribute that hasn't already been defined, so you can define what to do with it.

    A classic use case:

    class A(dict):
        def __getattr__(self, name):
           return self[name]
    a = A()
    # Now a.somekey will give a['somekey']
    

    Caveats and use of __getattribute__

    If you need to catch every attribute regardless whether it exists or not, use __getattribute__ instead. The difference is that __getattr__ only gets called for attributes that don't actually exist. If you set an attribute directly, referencing that attribute will retrieve it without calling __getattr__.

    __getattribute__ is called all the times.

提交回复
热议问题