Back to Python Mastery
AdvancedAdults
Object-Oriented Python
Object-Oriented Programming (OOP) is a powerful paradigm for structuring your applications. It's based on the concept of "objects," which can contain data and code.
The blueprint for an object is called a 'class'. Let's define a class for a 'Car':
The
Now, we can create 'instances' of the Car class:
'my_car' and 'your_car' are both objects of the Car class, but they have different data.
We can call methods on these objects:
OOP helps you model real-world things and manage complexity in large applications.
The blueprint for an object is called a 'class'. Let's define a class for a 'Car':
class Car:def __init__(self, brand, model):self.brand = brandself.model = modeldef display_info(self):print(f"{self.brand} {self.model}")The
__init__ method is a special method that runs when you create a new object from the class. self refers to the instance of the object itself.Now, we can create 'instances' of the Car class:
my_car = Car("Tesla", "Model 3")your_car = Car("Ford", "Mustang")'my_car' and 'your_car' are both objects of the Car class, but they have different data.
We can call methods on these objects:
my_car.display_info() # Prints "Tesla Model 3"your_car.display_info() # Prints "Ford Mustang"OOP helps you model real-world things and manage complexity in large applications.
Create a Car Class
Define a Car class with a brand and model. The __init__ method should store them as attributes.