What does self do?

user775171 picture user775171 · Jul 14, 2011 · Viewed 10.5k times · Source

Possible Duplicate:
Python 'self' keyword

Forgive me if this is an incredibly noobish question, but I never did understand self in Python. What does it do? And when I see things like

def example(self, args):
    return self.something

what do they do? I think I've seen args somewhere in a function too. Please explain in a simple way :P

Answer

Triptych picture Triptych · Jul 14, 2011

It sounds like you've stumbled onto the object oriented features of Python.

self is a reference to an object. It's very close to the concept of this in many C-style languages. Check out this code:

class Car(object):

  def __init__(self, make):

      # Set the user-defined 'make' property on the self object 
      self.make = make

      # Set the 'horn' property on the 'self' object to 'BEEEEEP'
      self.horn = 'BEEEEEP'

  def honk(self):

      # Now we can make some noise!
      print self.horn

# Create a new object of type Car, and attach it to the name `lambo`. 
# `lambo` in the code below refers to the exact same object as 'self' in the code above.

lambo = Car('Lamborghini')
print lambo.make
lambo.honk()