Sobes.tech
Junior — Middle

Explain what a class is in the Python programming language and how it is used.

sobes.tech AI

Answer from AI

A class in Python is a template (or blueprint) for creating objects, which combines data (attributes) and functions (methods) that work with this data. Classes allow you to create your own data types, modeling real-world entities.

Example of using a class:

class Car:
    def __init__(self, brand, year):
        self.brand = brand  # instance attribute
        self.year = year

    def drive(self):
        print(f"{self.brand} is driving")

# Creating an object (instance of the class)
my_car = Car("Toyota", 2020)
my_car.drive()  # Will output: Toyota is driving

Thus, a class helps structure code by combining data and behavior in one place.