What is the use of self in Python?
Self in Python
Once you start learning python, you will come across the term “self”. The keyword called “self” is for using the attributes and methods in a class. Here, in this article, let’s us understand in-depth about self and know when to use it. ‘However, before that, let us know the topics we will be covering here:
- Why Use Self in Python?
- Is it Important to use Self in python?
- Python Class Self Constructor?
- Is Self in Python A Keyword?
Why use self in python?
The keyword self is for representing the instance of the class. Before getting deeper into our main topic, let’s recall the instance variable and class variable. Class variables are shared with the instances (object) which are created with the particular class.
Now, getting back to our main topic. The self is for accessing the attributes and methods of the class. It binds those attributes with the argument. In python, we can use methods to pass instance automatically, but not receive automatically.
Example:
Class phone(): def __init__(self, model, color): self.model = model self.color = color def show(self): print("Model is", self.model ) print("color is", self.color ) samsung= phone (“samsung”, “black”) redmi= phone(“redmi”, “white”) samsung.show() redmi.show()
Output:
Model is Samsung Color is black Model is redmi Color is white
Is It Important To Use Self In Python?
As said earlier, the self-representing the instance of the class. Unlike other languages, when you create a new object, it does not create instance methods. Thus, the instance method comes under the object. It is best to save memory.
Python Class Self Constructor
You can also use self to refer to a variable field within the class. Let’s have a look at an example.
class School: def __init__(self, Stella): self.name = Stella def get_person_name(self): return self.name
Here, the self indicates the variable (name) of the class( school). The name is variable is used only when the method is running and local only to the method. If you want a global variable declaration, then declare it outside the class.
Now, let us move on to understand whether the self is a keyword or not.
Is the self a keyword?
No!! Self is not a keyword. In a function, the self is a parameter and the user can use any other parameter instead of self. However, it is better to use self as it is for boosting the readability of code.
Example:
class hello: def show(bye): print("Say hello to everyone") object = hello() object.show()
Output:
Say hello to everyone
With this, we have come to end our tutorial in self. If have any doubts or require any clarification, then, don’t hesitate to contact us.