Chapter 7 — Object-Oriented Python
📚 Chapter Overview
Python is a multi-paradigm language, but its OOP features are incredibly flexible. In this chapter, you will learn how to create Classes and Objects, use the __init__ method for initialization, and implement Inheritance to reuse code.
Learning Objectives:
- Master Class and Object creation.
- Understand the
selfkeyword. - Implement Single and Multiple Inheritance.
7.1 Classes and the __init__ Method
Part 1 — Definition
A Class is like an object constructor, or a "blueprint" for creating objects. In Python, the __init__() function is a special method (Constructor) that is automatically called when a new object is created. The self parameter represents the instance of the object itself.
Part 2 — Syntax
class MyClass:
def __init__(self, val):
self.attr = val
obj = MyClass("Hello")
Part 3 — Example
Problem: Model a "User" with a username and a method to greet.
class User:
def __init__(self, username):
self.username = username
def greet(self):
print(f"Welcome back, {self.username}!")
u1 = User("ali_dev")
u1.greet()
Part 4 — Video
Video: Coming Soon
7.2 Inheritance in Python
Part 1 — Definition
Inheritance allows us to define a class that inherits all the methods and properties from another class. The Child Class inherits from the Parent Class. Python also supports Multiple Inheritance, where a class can inherit from more than one parent.
Part 2 — Syntax
class Parent: ...
class Child(Parent): ...
Part 3 — Example
Problem: Create a generic "Animal" class and a specific "Dog" class.
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def speak(self):
print("Dog barks")
my_dog = Dog()
my_dog.speak() # Output: Dog barks
Observation: The child class can override methods of the parent class to provide specific behavior.
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Build a "BankAccount" system using OOP.
Requirements
- Create a class
BankAccountwithownerandbalance. - Methods:
deposit(amount)andwithdraw(amount). - Withdrawal should only happen if funds are sufficient.
- Create a subclass
SavingsAccountwith aninterest_rateattribute.
Step-by-Step Process
- Define the base class and its constructor.
- Implement logic checks inside the withdrawal method.
- Inherit the savings class and add the new field.
Expected Deliverables
bank_oop.pysource file.