Google News
logo
Python Program to The self Parameter
In Python, `self` is a special parameter that refers to the current instance of the class. It is the first parameter of any instance method in a class, and it is used to access the attributes and methods of the current object.

Here is an example program to demonstrate the use of the `self` parameter :
Program :
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def get_name(self):
        return self.name
    
    def get_age(self):
        return self.age
    
    def set_name(self, name):
        self.name = name
    
    def set_age(self, age):
        self.age = age
    
    def display_info(self):
        print("Name:", self.name)
        print("Age:", self.age)

# Create a Person object and set its attributes
p = Person("John", 25)
p.set_name("Jane")
p.set_age(30)

# Display the object's attributes using the methods
print(p.get_name())
print(p.get_age())

# Display the object's attributes using the display_info() method
p.display_info()
Output :
Jane
30
Name: Jane
Age: 30
In this program, we defined a `Person` class with an `__init__()` method to initialize the `name` and `age` attributes of the object. We also defined several methods to get and set the attributes, as well as a `display_info()` method to print out the object's attributes.

We then created a `Person` object named `p` with the name "John" and age 25. We used the `set_name()` and `set_age()` methods to change the object's attributes to "Jane" and 30, respectively. Finally, we used the `get_name()`, `get_age()`, and `display_info()` methods to access and display the object's attributes.