In Python, variables inside a class can be classified into class variables and instance variables.
The difference lies in how they are shared across objects.
Class Variables
- Belong to the class itself.
- Shared across all instances of the class.
- Changing a class variable affects all objects (unless shadowed by an instance variable).
Example:
class MyClass:
class_variable = 0 # Class variable
def __init__(self):
MyClass.class_variable += 1
def print_class_variable(self):
print(MyClass.class_variable)
obj1 = MyClass()
obj2 = MyClass()
obj1.print_class_variable() # Output: 2
obj2.print_class_variable() # Output: 2
Instance Variables
- Belong to a specific object (instance).
- Each instance has its own copy.
- Changing one instance variable does not affect others.
Example:
class MyClass:
def __init__(self, name):
self.name = name # Instance variable
def print_name(self):
print(self.name)
obj1 = MyClass("John")
obj2 = MyClass("Jane")
obj1.print_name() # Output: John
obj2.print_name() # Output: Jane
Key Differences
Feature | Class Variable | Instance Variable |
---|---|---|
Scope | Shared by all instances | Unique to each instance |
Declaration | Inside the class, but outside methods | Inside __init__ or other instance methods |
Access | Via ClassName.variable or self.variable |
Always via self.variable |
Modification Effect | Affects all objects (unless overridden) | Affects only that object |
When to Use
- Use class variables for values common to all objects (e.g., counter, configuration).
- Use instance variables for values unique to each object (e.g., name, age, balance).
👉 Next tutorial: Python Decorators