MyInternships.in

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.

Instance variables per object
Python
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.

A shared class variable
Python
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)
Output
Output
TechNova TechNova
TechNova Ltd TechNova Ltd
⚠️

If 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.

AspectInstance VariableClass Variable
Definedinside methods via self.xinside class body, outside methods
Storageseparate copy per objectone copy shared by all objects
Typical usename, age, price — unique datacompany, tax_rate — common data
Accessself.x or object.xClassName.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.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships