w3resource

How to access instance variables within Python class methods?

Accessing instance variables within Python class methods

Python class methods can access instance variables using the 'self' keyword. The 'self' keyword refers to the current instance of the class and allows you to access and manipulate instance variables within class methods.

Example: Access instance variables within a class method

class Student:
    def __init__(self, value):
        self.instance_var = value
    def display(self):
        print("Instance variable value:", self.instance_var)
    def update_instance_var_value(self, new_value):
        self.instance_var = new_value
# Create an object of Student
std_obj = Student(12)
# Access and display instance variable using the display() method
std_obj.display()  # Output: Instance variable value: 12
# Update instance variable using the update_instance_var() method
std_obj.update_instance_var_value(14)
# Display instance variable again to see the updated value
std_obj.display()  # Output: Instance variable value: 14

In this example, we have a class "Student" with an instance variable 'instance_var'. The 'display()' method prints the value of the instance variable. The 'update_instance_var_value()' method modifies the instance variable value.

Within both the 'display()' and 'update_instance_var_value()' methods, we use the 'self' keyword to access the 'instance_var'. This allows us to read and modify instance variable values within the class methods. This also ensures that each instance of the class maintains its own independent state.



Follow us on Facebook and Twitter for latest update.