What does he do?

Possible duplicate:
Python keyword 'self'

Forgive me if this is an incredibly Nubian question, but I never understood myself in Python. What does it do? And when I see things like

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

what are they doing? I think I saw the arguments somewhere in the function. Please explain in a simple way: P

+7
source share
3 answers

It sounds like you've come across Python object-oriented features.

self - a reference to an object. This is very close to the concept of this in many C-style languages. Check 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() 
+12
source

self is a reference to an instance of the class that the method (the example function in this case) has.

You want to take a look at the Python docs in the class system for a complete introduction to the Python class system. You will also want to look at these answers for other questions about the topic on https://stackoverflow.com/a/212960/220 .

+5
source

Self is a reference to an instance of the current class. In your example, self.something refers to the something property of an example class object.

+3
source

All Articles