Python Practice › OOP Programs › Program 2

Instance variables

EasyOOP Programs · 2 of 48

Write a Python class with instance variables and show that each object has its own values.

Advertisement
Output
Tata red
Honda black
{'brand': 'Tata', 'colour': 'red'}

Approach

  1. Set the variables on self in __init__.

Solution

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

More oop programs

← All 48 OOP Programs

Leave a Comment