Classes

self is the instance of the object. By using self, we can access the attributes and methods of the class in python.

Let's upgrade the example from the previous tutorial:

#Self class Welcome(object): def __init__(self, what_to_say): self.set_sentence(what_to_say) def set_sentence(self, what_to_say): self.sentence = what_to_say.upper() def say(self): print(self.sentence) #create a welcome object. what_to_say parameter is passed as "I love Python Tutorial" x = Welcome("I love Python Tutorial") x.say() #using the set_sentence() method to change the sentence x.set_sentence("Hello, World!") x.say()

Let's go through the script above:
Creating the Welcome class

  1. We created a Welcome class.
    The class gets the parameter - what_to_say
  2. We created an __init__ method.
    The method call set_sentence() method and pass the what_to_say parameter.
    As you can see later, this method edits the sentence attribute.
  3. We created the method set_sentence().
    The method edit the sentence attribute.
  4. We created a say method.
    This method prints out the sentence attribute.
Creating an object
  1. We created a Welcome object and passed "I love Python Tutorial".
  2. "I love Python Tutorial" is set to be the sentence attribute.
  3. We use the say() method and "I love Python Tutorial" is printed.
  4. We edit the sentence attribute with the set_sentence method.
  5. We use the say() method again.

Self - is the first parameter in every method of a class! Self says that the method operates on the object itself.

Exercise

  1. Create a class that gets the input age.
  2. Create a method that let you change the age
  3. Create init method that call the first method and sets the age
  4. Create an object
  5. Change the age

#Create a new class #Change the age