Python method as argument

So, I know that in python everything is an โ€œobjectโ€, which means that it can be passed as an argument to a method. But I'm trying to figure out exactly how this works. So I tried the following example:

class A: def __init__(self): self.value = 'a' def my_method(self) print self.value class B: def __init__(self): self.values = 'b' def my_method(self, method): method() a = A() b = B() b.my_method(a.my_method) 

Now it was first written to see how everything works. I know that I must, for example, check if the argument my_method callable. Now my question is:

How exactly is the method passed here? I mean the output I get is "a", so I assume that when the object method is passed as a parameter, so what is the actual object? In this case, when I pass a.my_method , an instance of a is also passed?

+7
source share
4 answers

When accessing a.my_method Python sees that it is an attribute of the class and that a.my_method has the __get__() method, so it calls A.my_method.__get__(a) , this method creates a new object (the "bound" method) that contains both a link to a.my_method and a link to a . When you call the bound method, it passes the call back to the base method.

This happens every time you call a method, whether you call it directly or, as in your code, delay the actual call until the end. You can find a more detailed description of the descriptor protocol, as is known at http://docs.python.org/reference/datamodel.html#descriptors

+8
source

How exactly did this method go here?

It is easy to answer: in Python everything is an object :) Also functions / methods that are concrete objects of a function that can be passed as parameters.

In this case, when I pass m.m_method, is instance a passed as well?

Yes, in this case, an instance of a is also passed, although it is built into the function object and cannot be restored. On the contrary, you can pass this function and provide it with an instance. Consider the following example:

 b = B() func = A.my_method # Attention, UPPERCASE A func(b) 

This will call a classes my_method with instance B

+4
source

Functions are "first-class objects" in Python. This means that the function is an object, as well as a list or an integer. When you define a function, you actually bind the function object to the name that you use in def.

Functions can be attached to other names or passed as parameters for functions (or stored in lists or ...).

source: http://mail.python.org/pipermail/tutor/2005-October/042616.html

+1
source

a.my_method does not return exactly the function that you defined in class A (you can get it through a.my_method ), but an object called a "bound method" that contains as the original function (or a "unbound method" in Python 2, IIRC) and the object from which it was extracted ( self argument).

+1
source

All Articles