Check if python instance method is the same function as provided by class

I have a variable that points to a specific class instance method. Suppose there is a class called Clientthat implements a method get. To Clientcreate a single instance of the name Client, and the variable get_funcis assigned to the client get.

For example, suppose I have the following simplified code:

class Client:
    def get(self):
        print("This is the get function!")

client = Client()
get_func = client.get

I have little actual control over get_funcand how it is used, I can’t change that.

Now I want to make sure that it get_funchas Client.get.

The trivial test get_func == Client.getdoes not work, because it get_funcis a related method of a specific instance Client. I also cannot get the instance Clientdirectly (but the way to get the selfassociated method is a valid option if I knew how to do this)

+4
source share
1 answer

Client.get (Python 3), (Python 2). Client().get, , . - , , ( ), self. . Python , Python .

, , , , , __func__:

get_func.__func__ is Client.get   # Python 3
get_func.__func__ is Client.get.__func__ # Python 2, unwrap the unbound method

Python 2 3, :

def unwrap_method(f):
    return getattr(f, '__func__', f)

:

unwrap_method(get_func) is unwrap_method(Client.get)
+4

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


All Articles