What is "self"?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Wayne Sutton

    What is "self"?

    OK, I'm a newbie...
    I'm trying to learn Python & have had fun with it so far. But I'm having
    trouble following the many code examples with the object "self." Can
    someone explain this usage in plain english?

    Thanks,
    Wayne


  • Sam Pointon

    #2
    Re: What is "self&quot ;?

    self is the class instance that the bound function being called belongs
    to. This example should illustrate a bit.


    class Foo(object):
    def __init__(self, value):
    self.value = value # so the Foo instance now has an attribute,
    value

    def get_value(self) :
    return self.value # This gets the previously-set value
    attribute of the Foo instance

    bar = Foo(42)
    baz = Foo('101010')

    print bar.get_value() #Note that the self argument is implicit since
    this is a bound method.
    print
    print baz.get_value()

    The output is (or should be, as this is untested):
    42

    101010

    Comment

    • marduk

      #3
      Re: What is "self&quot ;?

      On Thu, 2005-09-22 at 21:36 -0400, Wayne Sutton wrote:[color=blue]
      > OK, I'm a newbie...
      > I'm trying to learn Python & have had fun with it so far. But I'm having
      > trouble following the many code examples with the object "self." Can
      > someone explain this usage in plain english?[/color]

      "self" references the object itself. It's usually also called "this" on
      other languages (C++ & Java I believe). In Python, when you define a
      class method, the reference to the object is passed explicitly rather
      than implicitly.

      Also, the name "self" is used by convention. You could use any name if
      you wanted, but if you want other people to understand your code then
      use "self".

      Is that plain English enough?

      Comment

      • Ron Adam

        #4
        Re: What is "self&quot ;?

        Wayne Sutton wrote:[color=blue]
        > OK, I'm a newbie...
        > I'm trying to learn Python & have had fun with it so far. But I'm having
        > trouble following the many code examples with the object "self." Can
        > someone explain this usage in plain english?
        >
        > Thanks,
        > Wayne[/color]


        I'll give it a try..

        When you have a class definition:

        class Person(object):
        def set_name(self, name):
        self.name = name

        The method "set_name", has no idea what your class instance is going to
        called at this point. But it will need to know when it's called. So
        for now "self" is just a argument waiting to be assigned a reference
        later just like any other function argument. You can actually call it
        anything you want but "self" is sort of a tradition.

        leader = Person()

        This creates an instance of your class and stores a reference to it in
        the name "leader". Now that that you have an instance with a name. You
        can use your class method to do something.

        leader.set_name ("John")

        When you call a method of an instance, Python translates it to...

        leader.set_name (leader, "John")

        So "self" in your method definition gets assigned a reference to
        "leader". "self" can then be used to access the other values and
        methods stored in your class instance. Or in this case store a value in
        your class instance. Basically "self" becomes a reference to the class
        instance it is in.

        self.name = name

        is the same as ...

        leader.name = name

        But we didn't know it was going to be called "leader" when we wrote the
        class. So self is a convienent place holder.


        I hope this helped.

        Cheers,
        Ron









        Comment

        • James Stroud

          #5
          Re: What is "self&quot ;?

          I'm sure there are answers to this out there, but I'm typing this one up so I
          can show it to people that I try to teach this language. They consistently
          get hung up on what self is. So here is my try:

          ==

          Self is one of those python concepts that new python programmers have a little
          difficulty with. It refers to the instance of the class that is calling the
          method. That's confusing, so let's do an example.

          Say you have a class called Thing

          class Thing:
          def __init__(self, aval):
          self.value = aval
          def doit(self, another_val):
          print "Time 'till end of world:", (self.value + another_val)


          You can instatiate the thing class

          athing = Thing(1)

          The object referenced by the name "athing" lives in your computers memory
          somewhere. The name "athing" is how we reference, or talk about, that object.
          Above, "doit" is a member function of the Thing class. How can we call doit?

          athing.doit(5)

          What happened here? Why did we need self in the definition of doit when we
          didn't obviously pass something that we could construe as self? Well, we did
          pass something we could construe as self, it was "athing". How is this? Well,

          athing.doit(5)

          is equivalent to (and shorthand for)

          Thing.doit(athi ng, 5)

          Here is a picture of what this did:

          def doit(self, another_val)
          ^ ^
          athing 5

          print "Time 'till end of world:", (self.value + another_val)
          ^ ^
          athing.value 5


          This complies with the signature of the "Thing.doit " member function. The
          compiler turned the shorthand "athing.doit(5) " into "Thing.doit(ath ing, 5)"
          for us, saving us a little typing in the process and making our code easier
          to read.

          So, when we talk use self as a name in class member functions, we are actually
          referencing the instance that was passed to the member function. So for this
          example "athing" and "self" reference the same object. If an instance called
          another_thing was passed, then another_thing and self would refence the same
          object:

          another_thing = Thing()
          Thing.doit(anot her_thing, 5) # same as another_thing.d oit(5)

          ==

          On Thursday 22 September 2005 18:36, Wayne Sutton wrote:[color=blue]
          > OK, I'm a newbie...
          > I'm trying to learn Python & have had fun with it so far. But I'm having
          > trouble following the many code examples with the object "self." Can
          > someone explain this usage in plain english?
          >
          > Thanks,
          > Wayne[/color]

          --
          James Stroud
          UCLA-DOE Institute for Genomics and Proteomics
          Box 951570
          Los Angeles, CA 90095


          Comment

          • Erik Max Francis

            #6
            Re: What is "self&quot ;?

            Ron Adam wrote:
            [color=blue]
            > When you call a method of an instance, Python translates it to...
            >
            > leader.set_name (leader, "John")[/color]

            It actually translates it to

            Person.set_name (leader, "John")

            --
            Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
            San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
            Extremes meet.
            -- John Hall Wheelock

            Comment

            • Roy Smith

              #7
              Re: What is "self&quot ;?

              Ron Adam <rrr@ronadam.co m> wrote:[color=blue]
              > You can actually call it anything you want but "self" is sort of a
              > tradition.[/color]

              That's true, but I think needs to be said a bit more emphatically. There's
              no reason to call it anything other than "self" and a newcomer to the
              language would be well advised to not try and be creative here. Using
              "self" is virtually universal, and calling it anything else will just lead
              to confusion by other people who have to read your code.

              Comment

              • Rick Wotnaz

                #8
                Re: What is &quot;self&quot ;?

                Roy Smith <roy@panix.co m> wrote in
                news:roy-DE5389.07461923 092005@reader1. panix.com:
                [color=blue]
                > Ron Adam <rrr@ronadam.co m> wrote:[color=green]
                >> You can actually call it anything you want but "self" is sort
                >> of a tradition.[/color]
                >
                > That's true, but I think needs to be said a bit more
                > emphatically. There's no reason to call it anything other than
                > "self" and a newcomer to the language would be well advised to
                > not try and be creative here. Using "self" is virtually
                > universal, and calling it anything else will just lead to
                > confusion by other people who have to read your code.[/color]

                I've long thought that Guido missed an opportunity by not choosing
                to use 'i' as the instance identifier, and making it a reserved
                word. For one thing, it would resonate with the personal pronoun
                'I', and so carry essentially the same meaning as 'self'. It could
                also be understood as an initialism for 'instance'. And, because it
                is shorter, the number of objections to its existence *might* have
                been smaller than seems to be the case with 'self' as the
                convention.

                And as a side benefit, it would make it impossible to use as a loop
                index a language feature that would be a huge selling point among a
                lot of experienced programmers.

                --
                rzed

                Comment

                • Jeff Schwab

                  #9
                  Re: What is &quot;self&quot ;?

                  Rick Wotnaz wrote:[color=blue]
                  > Roy Smith <roy@panix.co m> wrote in
                  > news:roy-DE5389.07461923 092005@reader1. panix.com:
                  >
                  >[color=green]
                  >>Ron Adam <rrr@ronadam.co m> wrote:
                  >>[color=darkred]
                  >>>You can actually call it anything you want but "self" is sort
                  >>>of a tradition.[/color]
                  >>
                  >>That's true, but I think needs to be said a bit more
                  >>emphaticall y. There's no reason to call it anything other than
                  >>"self" and a newcomer to the language would be well advised to
                  >>not try and be creative here. Using "self" is virtually
                  >>universal, and calling it anything else will just lead to
                  >>confusion by other people who have to read your code.[/color]
                  >
                  >
                  > I've long thought that Guido missed an opportunity by not choosing
                  > to use 'i' as the instance identifier, and making it a reserved
                  > word. For one thing, it would resonate with the personal pronoun
                  > 'I', and so carry essentially the same meaning as 'self'. It could
                  > also be understood as an initialism for 'instance'. And, because it
                  > is shorter, the number of objections to its existence *might* have
                  > been smaller than seems to be the case with 'self' as the
                  > convention.
                  >
                  > And as a side benefit, it would make it impossible to use as a loop
                  > index a language feature that would be a huge selling point among a
                  > lot of experienced programmers.[/color]

                  And an annoyance to others.

                  Comment

                  • Sion Arrowsmith

                    #10
                    Re: What is &quot;self&quot ;?

                    Rick Wotnaz <desparn@wtf.co m> wrote:[color=blue]
                    >I've long thought that Guido missed an opportunity by not choosing
                    >to use 'i' as the instance identifier, and making it a reserved
                    >word. For one thing, it would resonate with the personal pronoun
                    >'I', and so carry essentially the same meaning as 'self'. It could
                    >also be understood as an initialism for 'instance'. And, because it
                    >is shorter, the number of objections to its existence *might* have
                    >been smaller than seems to be the case with 'self' as the
                    >convention.[/color]

                    My first serious forays into Python, where no-one else was expected
                    to be maintaining the code, used 'I' instead of 'self' -- it's
                    shorter, stands out better, and 'I.do_something ()' reads more like
                    English than 'self.do_someth ing()' (unless, I suppose, you're
                    thinking in terms of message passing). Then I started working on
                    code which other people might need to look at, and got an editor
                    whose Python syntax highlighting pretended that 'self' was a
                    reserved word, and now all my old code looks odd. (But still
                    perfectly readable -- this is Python after all.)

                    --
                    \S -- siona@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
                    ___ | "Frankly I have no feelings towards penguins one way or the other"
                    \X/ | -- Arthur C. Clarke
                    her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump

                    Comment

                    • Terry Hancock

                      #11
                      Re: What is &quot;self&quot ;?

                      On Friday 23 September 2005 07:11 am, Rick Wotnaz wrote:[color=blue]
                      > I've long thought that Guido missed an opportunity by not choosing
                      > to use 'i' as the instance identifier, and making it a reserved
                      > word. For one thing, it would resonate with the personal pronoun
                      > 'I', and so carry essentially the same meaning as 'self'. It could
                      > also be understood as an initialism for 'instance'. And, because it
                      > is shorter, the number of objections to its existence *might* have
                      > been smaller than seems to be the case with 'self' as the
                      > convention.
                      >
                      > And as a side benefit, it would make it impossible to use as a loop
                      > index a language feature that would be a huge selling point among a
                      > lot of experienced programmers.[/color]

                      How exactly is that? Anybody who uses "i" as a variable name for
                      anything other than an innermost loop index is a sick and twisted
                      code sadist.

                      You'd prefer what? "count" or "kount" or "i_am_an_innerm ost_loop_index_ counter".
                      I mean "explicit is better than implicit", right?

                      Maybe Fortran warped my brain, but I just don't see the benefit here.
                      --
                      Terry Hancock ( hancock at anansispacework s.com )
                      Anansi Spaceworks http://www.anansispaceworks.com

                      Comment

                      • Rick Wotnaz

                        #12
                        Re: What is &quot;self&quot ;?

                        Terry Hancock <hancock@anansi spaceworks.com> wrote in
                        news:mailman.85 1.1127486762.50 9.python-list@python.org :
                        [color=blue]
                        > On Friday 23 September 2005 07:11 am, Rick Wotnaz wrote:[color=green]
                        >> I've long thought that Guido missed an opportunity by not
                        >> choosing to use 'i' as the instance identifier, and making it a
                        >> reserved word. For one thing, it would resonate with the
                        >> personal pronoun 'I', and so carry essentially the same meaning
                        >> as 'self'. It could also be understood as an initialism for
                        >> 'instance'. And, because it is shorter, the number of
                        >> objections to its existence *might* have been smaller than
                        >> seems to be the case with 'self' as the convention.
                        >>
                        >> And as a side benefit, it would make it impossible to use as a
                        >> loop index a language feature that would be a huge selling
                        >> point among a lot of experienced programmers.[/color]
                        >
                        > How exactly is that? Anybody who uses "i" as a variable name
                        > for anything other than an innermost loop index is a sick and
                        > twisted code sadist.
                        >
                        > You'd prefer what? "count" or "kount" or
                        > "i_am_an_innerm ost_loop_index_ counter". I mean "explicit is
                        > better than implicit", right?
                        >
                        > Maybe Fortran warped my brain, but I just don't see the benefit
                        > here. --[/color]

                        Oh, 'ix' would be fine. Single-letter loop counters are also semi-
                        fine if that is in fact their only use. It too-frequently happens
                        that at some point the handy 'i' identifier is used outside the
                        loop (for another placeholder), and its value is tromped by an
                        intervening loop. Not terribly difficult to discover, but then
                        what? When you're maintaining code, even a two-character index is a
                        *lot* easier to find in source code and replace as needed.

                        --
                        rzed

                        Comment

                        • Peter

                          #13
                          Re: What is &quot;self&quot ;?

                          Terry Hancock wrote:
                          [color=blue]
                          >On Friday 23 September 2005 07:11 am, Rick Wotnaz wrote:
                          >
                          >[color=green]
                          >>I've long thought that Guido missed an opportunity by not choosing
                          >>to use 'i' as the instance identifier, and making it a reserved
                          >>word. For one thing, it would resonate with the personal pronoun
                          >>'I', and so carry essentially the same meaning as 'self'.
                          >>[/color][/color]
                          Not realy.
                          [color=blue][color=green]
                          >> It could
                          >>also be understood as an initialism for 'instance'.
                          >>[/color][/color]
                          MUCH better then trying to make it refer to "i" as in "me", but still.
                          [color=blue][color=green]
                          >>And, because it
                          >>is shorter, the number of objections to its existence *might* have
                          >>been smaller than seems to be the case with 'self' as the
                          >>convention.
                          >>
                          >>[/color][/color]
                          Humm... maybe. But would reap the fact that i does not have the same
                          exact meaning of self.
                          With the word self, it is possable to change a feature of yourSELF, but
                          try saying you changed a feature of "yourI", some internal logic in the
                          programmers brain is going to go off, and if the programmer is tired and
                          trying to finish something up but has that kind of internal confusion,
                          as suttle as it may be, he will get burnt out and have to wait intill
                          the next day.
                          [color=blue][color=green]
                          >>And as a side benefit, it would make it impossible to use as a loop
                          >>index a language feature that would be a huge selling point among a
                          >>lot of experienced programmers.
                          >>
                          >>[/color]
                          >
                          >
                          >[/color]
                          You think thats a good thing? o.0.
                          I agree that sometimes you need to name your loop variables well, but
                          sometimes you only need a simple, temp loop variable.

                          I would expect such an aprouch to be more likely to be found in intercal
                          (http://www.catb.org/~esr/intercal/), rather then in Python.
                          [color=blue]
                          >How exactly is that? Anybody who uses "i" as a variable name for
                          >anything other than an innermost loop index is a sick and twisted
                          >code sadist.
                          >
                          >
                          >[/color]
                          Agreed, though to say "code sadist" is a little hard don't ya think? ;)
                          [color=blue]
                          >You'd prefer what? "count" or "kount" or "i_am_an_innerm ost_loop_index_ counter".
                          >I mean "explicit is better than implicit", right?
                          >
                          >
                          >Maybe Fortran warped my brain, but I just don't see the benefit here.
                          >[/color]
                          Me ither.

                          I am no english professor, but isn't the word "i" usualy pointed at
                          something you will, have, can, or can't do in english?
                          "me" or "self" or "this" or "my" or "cls" or "inst" are refering to just
                          the object, nothing more, nothing less (except for "my" which is like
                          referring to "something i own") and are much more human-comprehendable.
                          IMHO.
                          [color=blue]
                          >--
                          >Terry Hancock ( hancock at anansispacework s.com )
                          >Anansi Spaceworks http://www.anansispaceworks.com
                          >
                          >
                          >[/color]

                          Peter

                          Comment

                          • Terry Hancock

                            #14
                            Re: What is &quot;self&quot ;?

                            On Friday 23 September 2005 10:42 am, Peter wrote:[color=blue]
                            > Terry Hancock wrote:[color=green]
                            > >How exactly is that? Anybody who uses "i" as a variable name for
                            > >anything other than an innermost loop index is a sick and twisted
                            > >code sadist.
                            > >[/color]
                            > Agreed, though to say "code sadist" is a little hard don't ya think? ;)[/color]

                            I don't know, I thought it quite poetic. ;-)
                            [color=blue][color=green]
                            > >You'd prefer what? "count" or "kount" or "i_am_an_innerm ost_loop_index_ counter".
                            > >I mean "explicit is better than implicit", right?
                            > >
                            > >Maybe Fortran warped my brain, but I just don't see the benefit here.
                            > >[/color]
                            > Me ither.
                            >
                            > I am no english professor, but isn't the word "i" usualy pointed at
                            > something you will, have, can, or can't do in english?
                            > "me" or "self" or "this" or "my" or "cls" or "inst" are refering to just
                            > the object, nothing more, nothing less (except for "my" which is like
                            > referring to "something i own") and are much more human-comprehendable.
                            > IMHO.[/color]

                            Whoa, you totally lost me there, dude.

                            ;-)

                            --
                            Terry Hancock ( hancock at anansispacework s.com )
                            Anansi Spaceworks http://www.anansispaceworks.com

                            Comment

                            • Terry Hancock

                              #15
                              Re: What is &quot;self&quot ;?

                              On Friday 23 September 2005 10:41 am, Rick Wotnaz wrote:[color=blue]
                              > Oh, 'ix' would be fine. Single-letter loop counters are also semi-
                              > fine if that is in fact their only use. It too-frequently happens
                              > that at some point the handy 'i' identifier is used outside the
                              > loop (for another placeholder), and its value is tromped by an
                              > intervening loop. Not terribly difficult to discover, but then
                              > what? When you're maintaining code, even a two-character index is a
                              > *lot* easier to find in source code and replace as needed.[/color]

                              Sorry, but if you have to grep for it, your loop is TOO DARNED LARGE,
                              USE A FUNCTION CALL!

                              --
                              Terry Hancock ( hancock at anansispacework s.com )
                              Anansi Spaceworks http://www.anansispaceworks.com

                              Comment

                              Working...