Article by: Manish Methani
Last Updated: October 4, 2021 at 2:04pm IST
Python is an object-oriented programming language, which means that it uses classes and objects as its primary structure. In this tutorial, you will learn about Python classes and objects and how they can be used in your programs. We will also look at some examples of how to use classes and objects in Python.
A class in Python is a blueprint or a template for creating objects. It defines the attributes (variables) and methods (functions) of an object. An object, on the other hand, is an instance of a class. It represents a real-world entity and has its own unique set of attributes and methods.
To create a class in Python, you use the class keyword followed by the name of the class. The attributes and methods of the class are defined inside the class block.
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def get_make(self): return self.make def get_model(self): return self.model def get_year(self): return self.year
In this example, we created a class called Car that has three attributes: make, model, and year. We also defined three methods: get_make(), get_model(), and get_year().
To create an object in Python, you use the name of the class followed by parentheses. You can assign the object to a variable to use it later.
my_car = Car("Toyota", "Corolla", 2022)
In this example, we created an object called my_car from the Car class. We passed three arguments to the constructor of the Car class: make="Toyota", model="Corolla", and year=2022.
To access the attributes and methods of an object in Python, you use the dot notation. You type the name of the object followed by a dot and the name of the attribute or method.
print(my_car.get_make()) print(my_car.get_model()) print(my_car.get_year())
In this example, we accessed the attributes of the my_car object using the get_make(), get_model(), and get_year() methods.
Python classes and objects are an essential part of object-oriented programming. In this tutorial, you learned how to create a class, create an object, and access the attributes and methods of an object in Python. These skills will be useful for creating more complex programs in Python.