How to Create an Object in Python

Working in Python, you will often use built-in types. However, in many scenarios, you may need to create custom objects. This tutorial will guide you on how to create an object in Python. We will use Python’s built-in class keyword to define a class, and then create objects from this class, which are instances of the class.

Step 1: Define a Class

Let us begin by creating a class. A class is defined in Python using the class keyword. Here is a simple class definition:

The pass keyword is used here because Python expects code after a colon. If we don’t plan on writing any class code, we use pass to avoid an error.

Step 2: Create an Object

Now that we have a Car class, we can create objects, or instances, of this class. Here is how we create an object:

We created an object named my_car which is an instance of the Car class.

Step 3: Add Attributes

We can add attributes to the Car class. Attributes are characteristics of the class. We can add attributes by modifying our class definition:

These attributes can be accessed and modified using the dot syntax:

The Full Code

Output

red
blue

Conclusion

In this tutorial, we learned how to create a class using the class keyword, how to create an instance of this class, and how to add attributes to the class. As you can see, creating objects in Python can be done with just a few simple lines of code. As a next step, you could learn about methods, which are functions that can be added to a class to provide more functionality.