In Python, you can use Object-Oriented Programming (OOP) to create classes and objects, which are used to model real-world entities.
- A class is a blueprint for creating objects, and it defines the properties and methods that objects can have.
- An object is an instance of a class, and it has all the properties and methods defined in the class.
Below is a simple example that demonstrates how to create classes and objects:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Car: def __init__(self, make, model, year, color): self.make = make self.model = model self.year = year self.color = color def display_details(self): print("Make:", self.make) print("Model:", self.model) print("Year:", self.year) print("Color:", self.color) car = Car("Toyota", "Camry", 2020, "Red") car.display_details() |
Output:
Make: Toyota
Model: Camry
Year: 2020
Color: Red
In this example, we create a class called Car
that has four properties: make
, model
, year
, and color
. The __init__
method is a special method that is called when an object of the class is created. It initializes the properties of the object with the values passed as arguments.
We also define a method display_details
that prints the details of the car. Finally, we create an object of the class Car
and call the display_details
method on it to display its details.
This is just a simple example to show the basic structure of a class and object in Python. You can use classes and objects to model much more complex real-world entities, such as cars, employees, students, etc.