What are classes in Python?
sobes.tech AI
Answer from AI
Classes in Python are templates for creating objects (instances). They define the data structure (attributes) and behavior (methods) that will be inherent to objects created based on this class.
A class combines data and functions that work with this data into a single entity. This is the foundation of object-oriented programming in Python.
Main concepts:
- Object (Instance): A specific implementation of a class. Each object has its own attribute values.
- Attributes: Variables that store the data of the object.
- Methods: Functions defined within the class that can work with the object's attributes.
Example:
# Definition of the Car class
class Car:
def __init__(self, make, model, year):
# Object attributes
self.make = make
self.model = model
self.year = year
self.is_started = False
# Method to start the engine
def start_engine(self):
if not self.is_started:
print(f"The {self.year} {self.make} {self.model} engine started.")
self.is_started = True
else:
print("Engine is already running.")
# Method to stop the engine
def stop_engine(self):
if self.is_started:
print(f"The {self.year} {self.make} {self.model} engine stopped.")
self.is_started = False
else:
print("Engine is already stopped.")
# Creating objects (instances of the Car class)
car1 = Car("Toyota", "Camry", 2022)
car2 = Car("Honda", "Civic", 2021)
# Calling methods on objects
car1.start_engine()
car2.start_engine()
car1.stop_engine()
In this example, Car is a class. car1 and car2 are objects (instances) of this class. make, model, year, is_started are attributes. start_engine() and stop_engine() are methods. __init__ is a special constructor method called when a new object is created and used to initialize its attributes. self is a reference to the object itself.
Using classes allows structuring code, increasing its readability and reusability, and implementing principles of object-oriented design (encapsulation, inheritance, polymorphism).