Python Tutorial menu

Python Classes and Objects

A class is a blueprint, and an object is a real thing made from that blueprint.

Why Classes?

Imagine you are writing software for an institute. Every student has a name, a roll number and a course, and every student can pay fees or take a test. A class lets you describe all of this once. Then you create as many objects (students) as you need.

This style is called object-oriented programming (OOP).

Creating a Class and an Object

Example

python
class Student:
    institute = "Workownix"

s1 = Student()
print(s1.institute)
Output
Workownix

Student is the class. s1 is an object (also called an instance) of that class.

By convention, class names start with a capital letter and use CapitalCase, like BankAccount.

The __init__ Method

__init__ runs automatically every time you create a new object. Use it to give each object its own data.

Example

python
class Student:
    def __init__(self, name, course):
        self.name = name
        self.course = course

s1 = Student("Ayesha", "Python")
s2 = Student("Bilal", "Web Development")
print(s1.name, "-", s1.course)
print(s2.name, "-", s2.course)
Output
Ayesha - Python
Bilal - Web Development

self means "this object". self.name = name stores the name inside the object. The values stored this way are called attributes.

Methods

A method is a function inside a class. Its first parameter is always self.

Example

python
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            print("Not enough balance")
        else:
            self.balance -= amount

    def show(self):
        print(f"{self.owner}: Rs {self.balance}")

acc = BankAccount("Hamza", 5000)
acc.deposit(2000)
acc.withdraw(10000)
acc.withdraw(1500)
acc.show()
Output
Not enough balance
Hamza: Rs 5500

Changing and Deleting Attributes

Example

python
acc = BankAccount("Sara", 1000)
acc.balance = 3000
acc.show()
del acc.balance
Output
Sara: Rs 3000

You can change an attribute directly. del removes it from the object.

The __str__ Method

__str__ decides what print() shows for an object:

Example

python
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __str__(self):
        return f"{self.name} (Rs {self.price})"

p = Product("Headphones", 2500)
print(p)
Output
Headphones (Rs 2500)

Inheritance

A class can inherit everything from another class and then add or change things. The original is the parent class, and the new one is the child class.

Example

python
class Person:
    def __init__(self, name):
        self.name = name

    def introduce(self):
        return f"I am {self.name}"

class Teacher(Person):
    def __init__(self, name, subject):
        super().__init__(name)
        self.subject = subject

    def introduce(self):
        return f"I am {self.name} and I teach {self.subject}"

p = Person("Ali")
t = Teacher("Ms. Fatima", "Python")
print(p.introduce())
print(t.introduce())
Output
I am Ali
I am Ms. Fatima and I teach Python

super().__init__(name) calls the parent's __init__, so you do not repeat code. The child's introduce() replaces the parent's version. This is called overriding.

Key Words

WordMeaning
ClassThe blueprint
Object / instanceOne real item made from the class
AttributeData stored in an object
MethodA function that belongs to a class
InheritanceA child class reusing a parent class

Exercise

Exercise

What is the purpose of the __init__ method?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp