Editor

Python Program to Create a Class and an Object

Beginner · Classes and objects

A class is a blueprint that describes the data an object holds and the things it can do, and an object is one thing made from that blueprint. Data stored in an object is called an attribute, and a function defined inside a class is called a method. This program defines a Car class, makes two car objects from it, and calls their methods.

Program

class_and_object.py
class Car:
def __init__(self, brand, colour):
# __init__ runs when an object is created; self is the new object
self.brand = brand
self.colour = colour
self.speed = 0
def accelerate(self, amount):
self.speed += amount
print(f"{self.brand} speeds up to {self.speed} km/h")
def describe(self):
print(f"A {self.colour} {self.brand} going at {self.speed} km/h")
# Two objects made from the same class
car1 = Car("Maruti", "red")
car2 = Car("Tata", "blue")
car1.accelerate(40)
car2.accelerate(25)
car1.accelerate(20)
car1.describe()
car2.describe()
print("car1 is an object of the class", type(car1).__name__)
Output
Maruti speeds up to 40 km/h
Tata speeds up to 25 km/h
Maruti speeds up to 60 km/h
A red Maruti going at 60 km/h
A blue Tata going at 25 km/h
car1 is an object of the class Car

How it works

  1. class Car: defines the blueprint, and Car("Maruti", "red") creates an object from it.
  2. __init__ is the constructor: it runs automatically for each new object and stores its brand, its colour and a starting speed of 0 as attributes.
  3. self is the object a method is working on, so self.speed is that particular car's speed.
  4. Calling car1.accelerate(40) changes only car1, which is why the two cars end up at different speeds.
  5. type(car1).__name__ gives the name of the class the object was made from.

Another way to write it

Class attributes and __str__

Class attributes and __str__
class Car:
wheels = 4 # a class attribute, shared by every car
count = 0
def __init__(self, brand):
self.brand = brand # an instance attribute, one per car
Car.count += 1
def __str__(self):
return f"{self.brand} with {self.wheels} wheels"
cars = [Car("Maruti"), Car("Tata"), Car("Honda")]
for car in cars:
print(car) # print() uses __str__
print("Cars made:", Car.count)
Output
Maruti with 4 wheels
Tata with 4 wheels
Honda with 4 wheels
Cars made: 3

wheels and count belong to the class itself, so every car shares them, and __str__ decides what print(car) shows instead of something like <__main__.Car object at 0x...>.

Try it yourself

Add a brake(amount) method that lowers the speed, but never below 0.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises