Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method in tuple requires explicit `self` argument

Tags:

python

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 this doesn't:

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

MyClass().g()

since it needs an argument self.ff[0](self):

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

Is not self.ff[0] == self.f as in the previous case self.ff == self.f ?

like image 900
Ruggero Turra Avatar asked Feb 08 '16 23:02

Ruggero Turra


1 Answers

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

For your first example you'll find that the function is wrapped to a (un)bound method which handles the self parameter for you:

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

while in your second example the function is used as a normal function:

>>> MyClass.ff[0]
<function f at 0x7f54>
>>> MyClass().ff[0]
<function f at 0x7f54>
like image 169
tynn Avatar answered Sep 28 '22 06:09

tynn