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:
1 2 |
class Car: pass |
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:
1 |
my_car = Car() |
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:
1 2 3 |
class Car: color = 'red' brand = 'Toyota' |
These attributes can be accessed and modified using the dot syntax:
1 2 3 |
print(my_car.color) # red my_car.color = 'blue' print(my_car.color) # blue |
The Full Code
1 2 3 4 5 6 7 8 |
class Car: color = 'red' brand = 'Toyota' my_car = Car() print(my_car.color) # output: red my_car.color = 'blue' print(my_car.color) # output: blue |
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.