How to create Python classes and objects

Python classes are like construction plans or templates. You can use them to write reusable code in the form of class attributes and methods.

What are Python classes?

A class is an abstract concept that outlines attributes 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 attributes 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 automatically be transferred 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 constructor __init__, which is invoked upon object creation, initialising two attributes: attribute1 and attribute2. The my_method method returns a formatted string containing the values of these attributes.

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

object1 = MyClass("Value 1", "Value 2")
result = object1.my_method()
python
Web Hosting
Secure, reliable hosting for your website
  • 99.9% uptime and super-fast loading
  • Advanced security features
  • Domain and email included

Examples of how to use Python classes

Python classes can create complex systems and relationships 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 implemented, it returns a string that represents a user-friendly representation 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 displaying a person’s name and age. When print(person1) is executed, it automatically 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 operations 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 initialisation. 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 corresponding values.

Changing the properties of objects

The . dot operator can be used to access the specific attributes 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 properties of an object.

del person1.name
python
Note

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

Was this article helpful?
Page top