to pass self or not to pass self

lallous elias.bachaalany at gmail.com
Mon Mar 15 12:39:50 EDT 2010


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' ?
Thanks,
Elias


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /