MyMisPal
← Python lessons
Lesson 12 of 13

Object-oriented programming

A class is a blueprint that bundles data and behaviour. Think of it like a table design: attributes are the columns, an object is a row with values, and methods are what it can do.

PYTHON
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def give_raise(self, percent):
        self.salary += self.salary * percent / 100

    def __str__(self):
        return f"{self.name}: {self.salary:.0f} SAR"

lina = Employee("Lina", 13500)
lina.give_raise(10)
print(lina)

__init__ runs automatically when you create an object, and self refers to the object itself. __str__ decides how it prints.

Inheritance: a new class takes everything from an existing one and adds to it:

PYTHON
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def monthly_cost(self):
        return self.salary

class Manager(Employee):
    def __init__(self, name, salary, bonus):
        super().__init__(name, salary)
        self.bonus = bonus

    def monthly_cost(self):
        return self.salary + self.bonus

team = [Employee("Sara", 9500), Manager("Khalid", 18000, 3000)]
for person in team:
    print(person.name, person.monthly_cost())

Exercises

Exercise 1

Write a Product class with name, price and qty, and a total() method returning price times quantity.

Exercise 2

Add withdraw(amount) to BankAccount: if the amount is more than the balance, print Insufficient funds; otherwise subtract it.

Spotted a mistake on this page, or have an idea to improve the site?