Overwrite __getattribute__ for instance?

It seems to me a little complicated. I once managed to rewrite an instance method using something like:

def my_method(self, attr):
    pass

instancemethod = type(self.method_to_overwrite)
self.method_to_overwrite = instancemethod(my_method, self, self.__class__)

which worked very well for me; but now I'm trying to overwrite the instance function __getattribute__(), which does not work for me for the reason that the method seems

<type 'method-wrapper'>

Is there anything you can do? I could not find decent Python documentation on method-wrapper.

+3
source share
4 answers

I believe the wrapper method is a wrapper around a method written in C.

+1
source

? , , , , , . , , __getattribute__ , Python , , .

, :

class FunkyAttributeLookup(object):
    def __getattribute__(self, key):
        try:
            # Lookup the per instance function via objects attribute lookup
            # to avoid infinite recursion.
            getter = object.__getattribute__(self, 'instance_getattribute')
            return getter(key)
        except AttributeError:
            return object.__getattribute__(self, key)

f = FunkyAttributeLookup()
f.instance_getattribute = lambda attr: attr.upper()
print(f.foo) # FOO

, , , , self.

 #descriptor protocol
 self.method_to_overwrite = my_method.__get__(self, type(self))
 # or curry
 from functools import partial
 self.method_to_overwrite = partial(my_method, self)
+5

, , __getattribute__() - .

+3

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


All Articles