Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python method as argument

Tags:

python

So I know in python everything is an 'object' meaning that it can be passed as an argument to a method. But I'm trying to understand how exactly does this work. So I was trying out 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 first this was written just to see how things work. I know I should for example check if my_method 's argument is callable. Now my question is:

How exactly is the method passed here? I mean the output I'm recieving is 'a' so I'm guessing that when a object method is passed as parameter so is the actual object ? In this case when I pass a.my_method the instance a is also passed ?

like image 620
Bogdan Avatar asked Aug 18 '11 12:08

Bogdan


2 Answers

When you access a.my_method Python sees that it is an attribute of the class and that A.my_method has a method __get__() so it calls A.my_method.__get__(a), that method creates a new object (the 'bound method') which contains both a reference to A.my_method and a reference to a itself. When you call the bound method it passes the call back through to the underlying method.

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

like image 96
Duncan Avatar answered Oct 20 '22 23:10

Duncan


How exactly is the method passed here?

This is easily answered: in Python, everything is an object :) Also functions/methods, which are specific function objects which can be passed as parameters.

In this case when I pass a.my_method the instance a is also passed?

Yes, in this case the instance a is also passed, though embedded in the function object and cannot be retrieved. On the contrary you could pass the function itself and supply it with an instance. Consider the following example:

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

This would call the A classes method my_method with an instance of B.

like image 28
Constantinius Avatar answered Oct 20 '22 23:10

Constantinius