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
We created a Welcome class.
The class gets the parameter - what_to_say
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.
We created the method set_sentence().
The method edit the sentence attribute.
We created a say method.
This method prints out the sentence attribute.
- We created a Welcome object and passed "I love Python Tutorial".
- "I love Python Tutorial" is set to be the sentence attribute.
- We use the say() method and "I love Python Tutorial" is printed.
- We edit the sentence attribute with the set_sentence method.
- We use the say() method again.
- Create a class that gets the input age.
- Create a method that let you change the age
- Create init method that call the first method and sets the age
- Create an object
- Change the age
#Create a new class #Change the age