[PYTHON] __Getattr__ and __getattribute__ to customize the acquisition of object attributes by dots

Getting attributes with .

I think that the attributes of objects such as variables and methods defined in the class statement are usually acquired by .. For example, suppose you define the following class.

python


class Foo:
    def __init__(self):
        self.foo = "foo"
        self.bar = "bar"

The attributes foo and bar of the instance foo of Foo can be obtained with ..

python


>>> foo = Foo()
>>> foo.foo
'foo'
>>> foo.bar
'bar'

This . behavior can be customized using the special attributes __getattr__ and __getattribute__ methods.

Customization with __getattr__

If you define __getattr__, when you try to get an attribute in ., the usual name search is done first, and if the specified attribute is still not found, __getattr__ is called and the returned value is used. Returns as that attribute.

The following class Foo defines __getattr__ to always return the member variable foo.

python


class Foo:

    def __init__(self):
        self.foo = "foo"
        self.bar = "bar"
    
    def __getattr__(self, name):
        return self.foo

The instance foo of Foo has a member variable called self.bar, so foo.bar returns self.bar, but there is no member variable called self.anything. So self.__ getattr__ ("anything") is executed and self.foo (ie the string " foo ") is returned.

python


>>> foo = Foo()
>>> foo.foo
'foo'
>>> foo.bar
'bar'
>>> foo.anything
'foo'

Customization with __getattribute__

If __getattribute__ is defined, this method will be called whenever you try to get an attribute in .. In the definition of __getattribute__, if you try to get the attribute of that object using ., your own __getattribute__ will be called recursively, so to avoid that, the superclass ʻobject Use __getattribute__ of`.

python


class Bar:

    def __init__(self):
        self.foo = "foo"
        self.bar = "bar"
    
    def __getattribute__(self, name):
        return object.__getattribute__(self, "foo")

As you can see from the following execution result, the instance bar of Bar has a member variable called self.bar, but even if it is bar.bar, it is __getattribute__. self.foo(ie the string" foo "`) is returned.

python


>>> bar = Bar()
>>> bar.foo
'foo'
>>> bar.bar
'foo'
>>> bar.anything
'foo'

Built-in functions getattr and hasattr

The built-in functions getattr and hasattr are based on attribute acquisition customized with __getattr__ and __hasattr__. So getting the attributes of an object with getattr is the same as getting it with .. If you check the instances of Foo and Bar in the above example, the output will be like this.

python


>>> getattr(foo, "bar")
'bar'
>>> getattr(bar, "bar")
'foo'

If __getattr__ or __getattribute__ returns a value no matter what attribute you specify (that is, ʻAttributeError does not occur), hasattralways returnsTrue`.

python


>>> hasattr(foo, "anything")
True
>>> hasattr(bar, "anything")
True

Recommended Posts

__Getattr__ and __getattribute__ to customize the acquisition of object attributes by dots
How to test the attributes added by add_request_method of pyramid
Python Note: When you want to know the attributes of an object
I tried to verify and analyze the acceleration of Python by Cython
Try to separate the background and moving object of the video with OpenCV
I want to customize the appearance of zabbix
[Blender] How to get the selection order of vertices, edges and faces of an object
I tried to verify the yin and yang classification of Hololive members by machine learning
[Python] Change the Cache-Control of the object uploaded to Cloud Storage
How to increase the processing speed of vertex position acquisition
Application of affine transformation by tensor-from basic to object detection-
An introduction to object orientation-let's change the internal state of an object
Hook to the first import of the module and print the module path
Debug by attaching to the Python process of the SSH destination
I want to know the features of Python and pip
Commands and files to check the version of CentOS Linux
How to get the pixel value of the point from the satellite image by specifying the latitude and longitude
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
How to get and set the NTP server name by DHCP
How to know the internal structure of an object in Python
[Cloudian # 9] Try to display the metadata of the object in Python (boto3)
Automatic acquisition of gene expression level data by python and R
[EC2] How to install chrome and the contents of each command
[Introduction to Python] I compared the naming conventions of C # and Python.
[Python] How to get the first and last days of the month
I summarized how to change the boot parameters of GRUB and GRUB2
To improve the reusability and maintainability of workflows created with Luigi
Convert the result of python optparse to dict and utilize it
Try to implement and understand the segment tree step by step (python)
Try to predict the triplet of boat race by ranking learning
I want to revive the legendary Nintendo combination by making full use of AI and HR Tech!