Python call method returned by __getattribute__

If this question has a duplicate, sorry, I did not find it, I will ask a question if someone does this.

I have this simple python class:

class NothingSpecial:
     @classmethod
     def meth(cls): 
          print("hi!")

And trying to get the method in different ways, I did:

a = (object.__getattribute__(NothingSpecial, 'meth'))

b = (getattr(NothingSpecial, 'meth'))

The question is:

b()

$ hi!

Refund, but when I do:

a()

TypeError: object 'classmethod' cannot be called

How can I execute a method a?

+4
source share
1 answer

You bypass the handle protocol and you have a method of an unrelated class.

The solution is to call the protocol if __get__method exists :

if hasattr(a, '__get__'):
    a = a.__get__(None, NothingSpecial)
a()

class , :

>>> a.__get__(None, NothingSpecial)
<bound method NothingSpecial.meth of <class '__main__.NothingSpecial'>>
>>> a.__get__(None, NothingSpecial)()
hi!

__getattribute__, , ; object.__getattribute__, type.__getattribute__:

>>> type.__getattribute__(NothingSpecial, 'meth')
<bound method NothingSpecial.meth of <class '__main__.NothingSpecial'>>

type(NothingSpecial).__getattribute__, __getattribute__ .

+5

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


All Articles