to pass self or not to pass self

TomF tomf.sessile at gmail.com
Mon Mar 15 18:42:41 CET 2010


On 2010-03-15 09:39:50 -0700, lallous <elias.bachaalany at gmail.com> said:

> Hello,
> 
> Learning Python from the help file and online resources can leave one
> with many gaps. Can someone comment on the following:
> 
> # ---------
> class X:
>     T = 1
> 
>     def f1(self, arg):
>         print "f1, arg=%d" % arg
>     def f2(self, arg):
>         print "f2, arg=%d" % arg
>     def f3(self, arg):
>         print "f3, arg=%d" % arg
> 
>     # this:
>     F = f2
>     # versus this:
>     func_tbl = { 1: f1, 2: f2, 3: f3 }
> 
>     def test1(self, n, arg):
>         # why passing 'self' is needed?
>         return self.func_tbl[n](self, arg)
> 
>     def test2(self):
>         f = self.f1
>         f(6)
> 
>         f = self.F
>         # why passing self is not needed?
>         f(87)
> 
> # ---------
> x = X()
> 
> x.test1(1, 5)
> print '----------'
> x.test2()
> 
> Why in test1() when it uses the class variable func_tbl we still need
> to pass self, but in test2() we don't ?
> 
> What is the difference between the reference in 'F' and 'func_tbl' ?

I recommend putting print statements into your code like this:

    def test1(self, n, arg):
        print "In test1, I'm calling a %s" % self.func_tbl[n]
        return self.func_tbl[n](self, arg)

    def test2(self):
        f = self.f1
        print "Now in test2, I'm calling a %s" % f
        f(6)


Bottom line: You're calling different things.  Your func_tbl is a dict 
of functions, not methods.

-Tom




More information about the Python-list mailing list