Skip to main content

CHAPTER 13: OBJECT-ORIENTED PROGRAMMING

13.1 CLASSES AND OBJECTS

13.1.1 Defining Classes

<PYTHON>

class Person:
def __init__(self, name, age):
self.name = name # Property
self.age = age # Property
def get_name(self): # Method
return self.name
def set_name(self, name):
self.name = name

13.1.2 Creating Objects

<PYTHON>

person1 = Person("John", 25)
person2 = Person("Jane", 30)

print(person1.get_name()) # Output: John
person1.set_name("Bob")

13.2 INHERITANCE

13.2.1 Basic Inheritance

<PYTHON>

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")

class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age) # Call parent constructor
self.student_id = student_id
def display(self):
super().display() # Call parent method
print(f"Student ID: {self.student_id}")

student = Student("John", 20, "S12345")
student.display()

13.2.2 Polymorphism

<PYTHON>

class Animal:
def speak(self):
pass

class Dog(Animal):
def speak(self):
return "Woof"

class Cat(Animal):
def speak(self):
return "Meow"

animals = [Dog(), Cat()]
for animal in animals:
print(animal.speak()) # Different output for same method

13.3 ENCAPSULATION

13.3.1 Private Attributes

<PYTHON>

class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private (double underscore)
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount

account = BankAccount(1000)
print(account.get_balance()) # OK
# print(account.__balance) # Error - private
account.deposit(500)

13.4 GETTERS AND SETTERS

13.4.1 Purpose

Control access to private attributes.

<PYTHON>

class Person:
def __init__(self, name):
self.__name = name
def get_name(self): # Getter
return self.__name
def set_name(self, name): # Setter
self.__name = name