Search⌘ K
AI Features

Class and Object

Explore how to define classes and create objects in Python to build modular and reusable code. Understand the roles of __init__ and self for initializing objects and managing attributes and methods. This lesson provides a foundational grasp of object-oriented programming concepts essential for Python developers.

A class is a blueprint for defining and creating objects. Objects, which will we will look at shortly, are actual instances of a class in a running program. For example, if we have a class to represent a person, then instances of that class representing actual persons, suppose Alice and Bob, will be objects. A class prescribes the set of characteristics known as attributes (these are the class variables) and behaviours known as methods (these are the class functions). Classes encapsulate attributes and methods to manipulate data, enabling modular, reusable, and organised code. The objects created from the class will possess all these attributes and methods.

Syntax for class definition

In Python, classes are created using the class keyword, followed by the name of the class and a colon. The class body is indented and it specifies the attributes and methods of that class. Let's look at an example to understand this better.

The example ...