Python Practice › OOP Programs › Program 2
Instance variables
Write a Python class with instance variables and show that each object has its own values.
Output
Tata red
Honda black
{'brand': 'Tata', 'colour': 'red'}Approach
- Set the variables on
selfin__init__.
Solution
class Car: def __init__(self, brand, colour): self.brand = brand self.colour = colour a = Car("Tata", "red")b = Car("Honda", "white")b.colour = "black"print(a.brand, a.colour)print(b.brand, b.colour)print(vars(a))Output
Tata red
Honda black
{'brand': 'Tata', 'colour': 'red'}Line by line
Line 8
Changing b.colour does not affect a; instance variables belong to one object.
Line 11
vars() shows an object’s instance variables as a dictionary.
Learn the concept
New to this topic? Read the lesson, then come back.