Python classes are like con­struc­tion plans or templates. You can use them to write reusable code in the form of class at­trib­utes and methods.

What are Python classes?

A class is an abstract concept that outlines at­trib­utes and methods for objects. A Python class acts as a template for creating concrete objects, which are instances of the class. For example, a Car, class could define at­trib­utes like colour and brand, along with methods such as __drive__ or __brake__.

While each object of a class can have unique attribute values, objects of the same class share methods and basic behaviour framework with other instances in the class. For example, the object my_car of the class Car can be created with the colour __red__ and the brand __Toyota__, but the methods __drive__ and __brake__ will auto­mat­ic­ally be trans­ferred to the instance.

How to create Python classes

In Python, you define classes using the keyword class.

class MyClass:
    # Constructor method called when creating an object
    def __init__(self, attribute1, attribute2):
        self.attribute1 = attribute1
        self.attribute2 = attribute2
    
    # Method defined within the class
    def my_method(self):
        return f"Attribute 1: {self.attribute1}, Attribute 2: {self.attribute2}"
python

The code above defines a class named MyClass. It has a con­struct­or __init__, which is invoked upon object creation, ini­tial­ising two at­trib­utes: attribute1 and attribute2. The my_method method returns a formatted string con­tain­ing the values of these at­trib­utes.

To derive an object from this class, use the class name followed by brackets:

object1 = MyClass("Value 1", "Value 2")
# Calling a method of the object
result = object1.my_method()
python
Web hosting
The hosting your website deserves at an un­beat­able price
  • Loading 3x faster for happier customers
  • Rock-solid 99.99% uptime and advanced pro­tec­tion
  • Only at IONOS: up to 500 GB included

Examples of how to use Python classes

Python classes can create complex systems and re­la­tion­ships between different entities. In the following sections, we’ll show you how to work with Python classes.

__str()__ function

The __str__() function in Python is a special method that you can define within Python classes. When im­ple­men­ted, it returns a string that rep­res­ents a user-friendly rep­res­ent­a­tion of an object. You can use the str() function directly on an object or combine it with a print() statement.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def __str__(self):
        return f"Name: {self.name}, Age: {self.age}"
person1 = Person("Alice", 30)
print(person1) # Output: Name: Alice, Age: 30
python

In the code above, the __str__() method within the Person class creates a formatted string dis­play­ing a person’s name and age. When print(person1) is executed, it auto­mat­ic­ally calls the __str__() method of the person1 object and outputs the string that is returned by the method.

Defining methods in Python classes

In Python, you can define methods within a class to perform op­er­a­tions on the objects of the class. These methods can then be called by the objects that are created.

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width
    
    def area(self):
        return self.length * self.width
    def perimeter(self):
        return 2 * (self.length + self.width)
# Creating an object of the class
my_rectangle = Rectangle(5, 10)
# Calling methods of the object
area = my_rectangle.area()
perimeter = my_rectangle.perimeter()
# Printing the calculated values
print("Area =", area) # Output: Area = 50
print("Perimeter =", perimeter) # Output: Perimeter = 30
python

In the Python example, we define the class Rectangle with two methods area() and perimeter(), which calculate the rectangle’s area and perimeter using the length and width provided during object ini­tial­isa­tion. In Python, self in a class method acts as a reference to the object, which the method is currently being applied to.

The object my_rectangle is created with a length of 5 and a width of 10. We then call the methods area() and perimeter() on this object to calculate the cor­res­pond­ing values.

Changing the prop­er­ties of objects

The . dot operator can be used to access the specific at­trib­utes of the object and update their values. You can assign new values directly to the attribute.

person1.name = "Sarah"
person1.age = 35
python

The keyword del is used to delete the prop­er­ties of an object.

del person1.name
python
Note

Remember that instance variables are different from Python class variables. Class variables are defined outside the con­struct­or and can only be changed by using the class name.

Go to Main Menu