Explain the variables inside and outside of a class __init__() function in Python.

In Python, variables can be defined inside and outside the __init__() function of a class. Variables outside the __init__() function are called class variables, while variables inside the __init__() function are called instance variables. Understanding the difference is crucial for proper object-oriented programming.

Class Variables vs Instance Variables

Class variables are shared among all instances of a class, while instance variables are unique to each object. Let's examine this with a practical example ?

Example

class MyClass:
    stat_elem = 456  # Class variable
    
    def __init__(self):
        self.object_elem = 789  # Instance variable

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
print("c1:", c1.stat_elem, c1.object_elem)
print("c2:", c2.stat_elem, c2.object_elem)
c1: 456 789
c2: 456 789

Changing Class Variables

When you modify a class variable, it affects all instances of that class ?

class MyClass:
    stat_elem = 456  # Class variable
    
    def __init__(self):
        self.object_elem = 789  # Instance variable

c1 = MyClass()
c2 = MyClass()

# Change the class variable
MyClass.stat_elem = 888

print("After changing class variable:")
print("c1:", c1.stat_elem, c1.object_elem)
print("c2:", c2.stat_elem, c2.object_elem)
After changing class variable:
c1: 888 789
c2: 888 789

Changing Instance Variables

When you modify an instance variable, it only affects that specific object ?

class MyClass:
    stat_elem = 456  # Class variable
    
    def __init__(self):
        self.object_elem = 789  # Instance variable

c1 = MyClass()
c2 = MyClass()

# Change class variable first
MyClass.stat_elem = 888

# Now change instance variable for c1 only
c1.object_elem = 777

print("After changing instance variable:")
print("c1:", c1.stat_elem, c1.object_elem)
print("c2:", c2.stat_elem, c2.object_elem)
After changing instance variable:
c1: 888 777
c2: 888 789

Key Differences

Aspect Class Variables Instance Variables
Location Outside __init__() Inside __init__()
Sharing Shared by all instances Unique to each instance
Access ClassName.variable self.variable
Memory One copy per class One copy per instance

Conclusion

Class variables are shared among all instances and defined outside __init__(), while instance variables are unique to each object and defined inside __init__(). Use class variables for data that should be the same across all instances, and instance variables for data specific to each object.

Updated on: 2026-03-24T19:38:24+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements