The method in the tuple requires an explicit argument of `self`

I want to understand why this code works:

class MyClass(object): def f(self): print "Hello" ff = f def g(self): self.ff() MyClass().g() 

while it is not:

 class MyClass(object): def f(self): print "Hello" ff = f, def g(self): self.ff[0]() MyClass().g() 

since he needs the argument self.ff[0](self) :

 TypeError: f() takes exactly 1 argument (0 given) 

Not self.ff[0] == self.f , as in the previous case self.ff == self.f ?

+7
python
source share
1 answer

You can see the difference when printing a member of your class.

In the first example, you will find that the function is bound to the (un) method, which processes the self parameter for you:

 >>> MyClass.ff <unbound method MyClass.f> >>> MyClass().ff <bound method MyClass.f of <__main__.MyClass object at 0x7f53>> 

and in the second example, the function is used as a regular function:

 >>> MyClass.ff[0] <function f at 0x7f54> >>> MyClass().ff[0] <function f at 0x7f54> 
+3
source share

All Articles