Changing __getattr__ during instance creation

I want to change __getattr__during class instance creation. For instance:

class AttrTest(object):
    def __init__(self):
        self.__getattr__ = self._getattr

    def _getattr(self, attr):
        print("Getting {}".format(attr))

I would expect it to look like this:

class AttrTest(object):
    def __getattr__(self, attr):
        print("Getting {}".format(attr))

But this is not so.

For example, when I run:

>>> at = AttrTest()
>>> at.test

I would expect both classes to print Getting test, but the upper class chose AttributeError.

Can it __getattr__not change in this way?

+4
source share
1 answer

For special methods, such as __getattr__, Python searches in the database (s) __dict__and not in the instance __dict__.

You can read more about this in the special search section of the data model documentation.

__getattr__, (json, pickle), , kwarg.

__getattr__. @property descriptors, .

+3

Source: https://habr.com/ru/post/1653953/


All Articles