Today you will learn:
By the end, you will be able to write your own classes to make complex programs organized and modular.
A class is a blueprint or template for objects.
An object is a concrete instance of that class.
Real-life example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(self.name + " is barking!")
Explanation:
class creates a class__init__ is the constructor (called when creating an object)self refers to the current objectself.
my_dog = Dog("Bello", 5)
"Bello" → name
5 → age
my_dog → object
my_dog.bark()
Output:
Bello is barking!
Explanation:
self.name accesses the attribute
my_dog.age = 6
print(my_dog.age)
Output:
6
Practice Tip:
class Car:
def __init__(self, brand, model, mileage=0):
self.brand = brand
self.model = model
self.mileage = mileage
def drive(self, km):
self.mileage += km
print("The car has driven. New mileage:", self.mileage)
my_car = Car("BMW", "X5")
my_car.drive(50)
car2 = Car("Audi", "A4", 20000)
car2.drive(100)
Output:
The car has driven. New mileage: 50
The car has driven. New mileage: 20100
Explanation:
mileage=0 is a default valueCar class with attributes: brand, model, mileagedrive(km) method