Class and Object
Learn about Python classes and objects, including their syntax, the __init__ method, and the self keyword.
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 below shows how to create a Person
class that can store a person's name and age and also print this information.
Get hands-on with 1200+ tech skills courses.