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
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
class Car:defines the blueprint, andCar("Maruti", "red")creates an object from it.__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.selfis the object a method is working on, soself.speedis that particular car's speed.- Calling
car1.accelerate(40)changes onlycar1, which is why the two cars end up at different speeds. type(car1).__name__gives the name of the class the object was made from.
Another way to write it
Class attributes and __str__
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises