Purpose of self in Python
In this article, we will learn about self in depth. While using Python, there is no escaping the use of self.
The most common misunderstanding with the word is that it is commonly mistaken as a keyword because of its use in different places.
In the example below, a class is created. The class has 2 functions. The first function has three attributes one of which is self. It can be seen how self is used.
class food(): def __init__(self, cake, price): self.cake = cake self.price = price def show(self): print("Cake is", self.cake ) print("Price is", self.price ) item_1 = food("Chocolate", "Rs. 500") item_2 = food("Red Velvet", "Rs. 700") item_1.show() item_2.show()
Output:
Cake is Chocolate Price is Rs. 500 Cake is Red Velvet Price is Rs. 700
Self is a convention. Self is just a parameter in the function. We can replace it with another parameter name.
In the example below, we can see that any attribute name can be used in place of self.
class food: def show(self_replacement): print("Here is an example of " "another parameter name being used in place of self") object = food() object.show()
Output:
Here is an example of another parameter name being used in place of self
Why is it necessary to use self?
- It increases the readability of code.
- It is used to access the attributes and methods of theĀ class in Python.
Leave a Reply