What is object-oriented programming?
What is object-oriented programming?
Object-oriented programming is a concept of system configuration.
It points that divide class by each thing, make software by defining relationship of thing and thing.
By the way, In programming, “object” mean data and collection of processes.
Three principles of object-oriented programming
Inheritance
Inheritance is a structure that summarize common part of class definition to other class.
Reason of to use inheritance is to improve reusability of code and scalability.
If you made two instances that sports car and taxi, you can summarize common parts that tyre, engine and handle, etc.
This is a merit of inheritance.
# Parent class
class Car:
def __init__(self, brand, tyre, engine, handle):
self.brand = brand
self.tyre = tyre
self.engine = engine
self.handle = handle
def start_engine(self):
print(f"{self.brand} engine started.")
def stop_engine(self):
print(f"{self.brand} engine stopped.")
def show_parts(self):
print(f"Tyre: {self.tyre}, Engine: {self.engine}, Handle: {self.handle}")
# Child class: SportsCar
class SportsCar(Car):
def __init__(self, brand, tyre, engine, handle, turbo=True):
super().__init__(brand, tyre, engine, handle) # Inherit from Car
self.turbo = turbo
def start_engine(self):
# Override parent method
print(f"{self.brand} roars to life with {'turbo boost' if self.turbo else 'standard power'}!")
# Child class: Taxi
class Taxi(Car):
def __init__(self, brand, tyre, engine, handle, fare_per_km):
super().__init__(brand, tyre, engine, handle)
self.fare_per_km = fare_per_km
def calculate_fare(self, distance):
return self.fare_per_km * distance
# --- Example usage ---
sports_car = SportsCar("Ferrari", "Pirelli", "V8", "Leather", turbo=True)
taxi = Taxi("Toyota", "Michelin", "Hybrid", "Plastic", fare_per_km=2.5)
sports_car.start_engine() # Ferrari roars to life with turbo boost!
sports_car.show_parts() # Tyre: Pirelli, Engine: V8, Handle: Leather
taxi.start_engine() # Toyota engine started.
print(f"Taxi fare for 10 km: ${taxi.calculate_fare(10)}")
Encapsulation
Encapsulation is a structure that can’t be changed as much as possible from other programs.
In using this structure, you can hide objects that don’t need to use directly from other objects.
Accordingly, Programs is less likely to break, And It’s easier to develop with many people too.
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # public attribute
self.__balance = balance # private attribute (name mangling)
# Public method to deposit money
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited ${amount}. New balance: ${self.__balance}")
else:
print("Deposit amount must be positive.")
# Public method to withdraw money
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew ${amount}. New balance: ${self.__balance}")
else:
print("Invalid withdrawal amount.")
# Public method to check balance (read-only)
def get_balance(self):
return self.__balance
# --- Example usage ---
account = BankAccount("Alice", 1000)
account.deposit(500) # Deposited $500. New balance: $1500
account.withdraw(200) # Withdrew $200. New balance: $1300
print(account.get_balance()) # 1300
# Direct access to __balance is not allowed:
# print(account.__balance) # AttributeError
Polymorphism
Polymorphism is a structure that use a part of inherited code.
In other words, It point a nature that can execute a different processing using same method by class.
In the following example, you can use same name method each class.
class Car:
def drive(self):
print("The car is driving on the road.")
class Boat:
def drive(self):
print("The boat is sailing on the water.")
class Plane:
def drive(self):
print("The plane is flying in the sky.")
# Function that works with any object that has a drive() method
def start_journey(vehicle):
vehicle.drive()
# --- Example usage ---
car = Car()
boat = Boat()
plane = Plane()
for v in (car, boat, plane):
start_journey(v)
# --- Output ---
# The car is driving on the road.
# The boat is sailing on the water.
# The plane is flying in the sky.
