Python OOP
Python Instance and Class Variables
Python objects can have instance variables, which are unique to each object, and class variables, which are shared by every object of that class.
Instance Variables
Instance variables are defined inside __init__ (or any method) using self.name = value. Each object gets its own independent copy, so changing one object's attribute never affects another object.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
e1 = Employee("Riya", 50000)
e2 = Employee("Karan", 60000)
e1.salary = 55000
print(e1.salary, e2.salary)Class Variables
Class variables are defined directly inside the class body, outside any method. They are shared across all objects — if one object changes it via the class name, every object sees the new value.
class Employee:
company = "TechNova"
def __init__(self, name, salary):
self.name = name
self.salary = salary
e1 = Employee("Riya", 50000)
e2 = Employee("Karan", 60000)
print(e1.company, e2.company)
Employee.company = "TechNova Ltd"
print(e1.company, e2.company)TechNova TechNova
TechNova Ltd TechNova LtdIf you write e1.company = "X" instead of Employee.company = "X", Python creates a new instance variable on e1 only, hiding the class variable for that object rather than changing the shared value.
| Aspect | Instance Variable | Class Variable |
|---|---|---|
| Defined | inside methods via self.x | inside class body, outside methods |
| Storage | separate copy per object | one copy shared by all objects |
| Typical use | name, age, price — unique data | company, tax_rate — common data |
| Access | self.x or object.x | ClassName.x or object.x |
Class variables are handy for counters, constants and configuration shared across every object, while instance variables hold each object's own unique data.
