In this Python article we want to learn about Introduction to Python Classes and Objects, so Python is popular powerful and high level programming language that is commonly used in different sections, including web development, data analysis and machine learning. so one of the best features of Python programming language is support of object oriented programming or OOP, because using OOP we can create reusable, modular code by organizing data and functions into objects.
In Python objects are created from classes, which define the properties and behavior of the object. so we can say that class is a blueprint or template for creating objects, and it can include attributes and methods that define the behavior of the object. after that the class is defined, you can create instances or we can say objects of that class, which are unique instances with their own data and behavior.
Now let’s learn that how we can define Python classes and objects, for defining Python class, we can use class keyword followed by the name of the class. for example this is simple Python class definition:
1 2 3 4 5 6 7 8 9 10 11 |
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def start(self): print("The car has started.") def stop(self): print("The car has stopped.") |
In the above example we have defined a Car class that has three attributes make, model and year. we have also defined two methods start() and stop(), which print messages indicating that the car has started or stopped.
After that you have defined a Python class, you can create objects or instances of that class using class constructor. for creating an object of the Car class you can do like this.
1 |
my_car = Car("Ford", "Mustang", 2023) |
This is the complete code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def start(self): print("The car has started.") def stop(self): print("The car has stopped.") my_car = Car("Ford", "Mustang", 2023) print(my_car.make) print(my_car.model) print(my_car.year) |
If you run this, you will see this result
So in the previous example we have accessed the attributes, now let’s learn that how we can access methods in Python Objects, you can access the attributes and methods using dot notation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def start(self): print("The car has started.") def stop(self): print("The car has stopped.") my_car = Car("Ford", "Mustang", 2023) print(my_car.stop()) print(my_car.start()) |
So we can say that Python classes and objects are fundamental part of object oriented programming in Python. by organizing data and functions into objects you can create reusable, modular code that is easier to maintain and scale.