Skip to content

Classes and Objects

Python is a language with support for object-oriented programming. This means you can model real-world elements as objects that have properties (attributes) and behaviors (methods), using classes as a blueprint to create them.


A class is a template or blueprint used to create objects (instances). It groups data and functions that operate on that data.

Class Definition
class Product:
pass

In this example, Product is the name of the class. For now, it has no attributes or methods.


The special method __init__ is the constructor of the class. It is automatically executed when you create a new instance (object) and is used to initialize the object’s attributes.

Constructor (__init__)
class Product:
def __init__(self, name, price):
self.name = name
self.price = price

When you create a new product with Product("Shoe", 50), the __init__ method assigns "Shoe" to self.name and 50 to self.price.


self is a reference to the object itself. It is used within the class’s methods to access or modify the attributes and to call other methods of the same object. It must always be the first parameter of any instance method, although you do not pass it explicitly when calling the method.

Usage of self
class Product:
def display_info(self):
print(self.name, self.price)

When you call p.display_info(), Python automatically passes the object p as an argument for self.


Let’s see a complete example of how to define a class, create an object, and use its methods:

Product Class Example
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def display_info(self):
print(f'Product: {self.name} | Price: ${self.price}')
# Create an object
p1 = Product('Shirt', 25.99)
# Use the method
p1.display_info()

Output:

Product: Shirt | Price: $25.99

  • A class is a blueprint for creating objects.
  • The __init__ method initializes the object’s attributes.
  • The self parameter allows access to the object’s attributes and methods.
  • You can create multiple objects from the same class, each with its own values.

Ready to create your own classes and objects? Practice modifying the examples!