understanding self

Albert Hofkamp hat at se-126.se.wtb.tue.nl
Thu Jul 8 04:16:19 EDT 2004


On Wed, 7 Jul 2004 19:24:14 -0400, bruce stockwell <JbUaNsK68 at cox.net> wrote:
> blink is a method of bruce because bruce is an instance of human. 
> Reading this silly code I can understand what is going on if self was 
> not included. Can anyone enlighten me as to why we have self?

ok, what about this?

def f():
   # do something
   return 5

class X:
   def f(self):
      # do something else
      return 4


   def doit(self):
      x=self.f()
      y=f()

The example is very silly, but when executing doit(), it is clear that x
will contain 4 and y will contain 5 afterwards.

Now if we drop self, we get

   def doit(self):
      x=f()
      y=f()

Now there is no difference between both calls any more. That means that
the computer does not understand that you are aiming for calling
different functions f() here.  We can agree that f() means the f in the
class, but then I cannot reach the global f any more, or vice versa. In
both cases, I lose expressiveness.


Albert
-- 
Unlike popular belief, the .doc format is not an open publically available format.



More information about the Python-list mailing list