What Is The Purpose Of The `self` Parameter? Why Is It Needed?

In this post, we will see The Purpose Of The `self` Parameter. Why Is It Needed it is a keyword that is used for accessing the variable or method of the same class as at the time of overriding when we want to access the method of the same class we use self in python and in java we use this keyword for the same thing.

Self

Self

It is a keyword that is used for referring to the variables of the same class for example look at the code given below where we can see how we have used the self keyword at different places

class Car:
    def __init__(self, make, model, year):
        self. make = make
        self. model = model
        self. year = year
    
    def start( self):
        print(f"{self. make} {self. model} ({self. year}) is starting.")
    
    def stop( self):
        print(f"{ self. make} {self. model} ({self. year}) is stopping.")

In the above code as we can see how the parameters of the init function have passed and the variables have passed the values of the local variable created there using the self keyword we can see the values of local variables will be the same as we passed in the parameter as we used self keyword to store the values.

similarly, we have a super keyword that is used to access the variable and method of the parent class and it might be used for calling the methods of the parent class in inheritance.

 

To learn more about self and super keywords and their uses along with purpose along with examples visit: Python self and super keyword comparisons.

To learn more about python programming and related tutorials on problems faced in programming along with concepts and examples visit: Python Tutorial – How to Use Global Variables in a Function | Python Programs Examples.

To learn more about different other programming languages like java, and MongoDB visit: beta python programming languages Solutions.

Leave a Comment

%d bloggers like this: