The self in Python
‘self’ lets us refer to an instance of a class, Let’s modify our previous Animal class example:
class Animal(object): name = None def speak(self): print "My name is ", self.name # Create an instance variable of the Animal class tiger = Animal() # Evoke the speak method tiger.speak()
My name is None
'self' is the class, and can be called from within the class and it's internal methods, and when creating a new instance.
We have created a new variable within the class and given it the 'None' value, asking the tiger to speak (tiger.speak()) evokes the speak() method and returns the string above, as expected self.name returns 'None'.
So how do we pass the name of the tiger to the speak method? Right after we define the tiger instance variable of the Animal class, we define the name to pass through to the method:
# Create an instance variable of the Animal class tiger = Animal() # Define the 'name' for the tiger instance tiger.name = 'John' # Evoke the speak method tiger.speak()
Output: My name is John