w3resource

What is the scope of instance variables?

Scope of instance variables in Python classes

Python instance variables are bound to the specific instance (object) of the class they are defined in. Instance variables are accessible and usable within the methods of the class. This allows each instance of the class to maintain its own independent state and data.

Instance variables are defined within the class, typically within the '__init()__' method (constructor), using the 'self' keyword. The 'self' keyword refers to the current instance of the class and is used to access and assign values to the instance variables.

Once an object is created from a class, it retains its own set of instance variables that are unique to that particular instance. Instance variables of one object do not affect instance variables of other objects created from the same class.

Example: Scope of instance variables

class Person:
    def __init__(self, value):
        self.instance_var = value

    def display(self):
        print("Instance variable value:", self.instance_var)

# Create two objects of MyClass
person1 = Person("Blaanid Vasilii")
person2 = Person("Jupp Hardy")

# Access and modify instance variables of each object
person1.display()  # Output: Instance variable value: Blaanid Vasilii
person2.display()  # Output: Instance variable value: Jupp Hardy

# Modify instance variables
person1.instance_var = "Zsazsa Irene"
person2.instance_var = "Takumi Zola"

# Display instance variable values again
person1.display()  # Output: Instance variable value: Zsazsa Irene
person2.display()  # Output: Instance variable value: Takumi Zola

In the example above, we have a class "Person" with an instance variable 'instance_var'. Two objects ('person1' and 'person2') are created from this class. Each object has its own separate copy of the instance_var, and modifying the value of instance_var for one object does not affect the other objects.



Follow us on Facebook and Twitter for latest update.