๐ข Lesson 4
๐ฐ What Is OOP?

Object-Oriented Programming (OOP) is a programming style where you organize code into objects that contain:
- Data (attributes)
- Functions (methods) that operate on that data
Python supports OOP using:
class
โ to define a blueprintobject
โ a real-world instance of a class
๐งฑ Example: Why Use OOP?
Instead of this:
pythonCopierModifiercar1_name = "Toyota"
car1_color = "Red"
Use this:
pythonCopierModifierclass Car:
def __init__(self, name, color):
self.name = name
self.color = color
car1 = Car("Toyota", "Red")
โ More organized, reusable, and scalable.
๐๏ธ Defining a Class
pythonCopierModifierclass Person:
def __init__(self, name, age):
self.name = name # attribute
self.age = age # attribute
def greet(self): # method
print(f"Hi, I'm {self.name} and I'm {self.age} years old.")
__init__
is the constructor (runs when object is created).self
refers to the instance (object itself).greet()
is a method.
๐ง Creating Objects
pythonCopierModifierperson1 = Person("Alice", 28)
person2 = Person("Bob", 35)
person1.greet() # Output: Hi, I'm Alice and I'm 28 years old.
person2.greet() # Output: Hi, I'm Bob and I'm 35 years old.
๐งฉ Key OOP Terms
Term | Meaning |
---|---|
class | Blueprint/template for creating objects |
object | Instance of a class |
__init__ | Constructor method (runs when object is created) |
self | Refers to the instance inside the class |
method | Function defined in a class |
attribute | Variable that belongs to an object |
๐ง Exercise 1: Simple Bank Account Class
pythonCopierModifierclass BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"{amount} deposited. New balance: {self.balance}")
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
print(f"{amount} withdrawn. New balance: {self.balance}")
else:
print("Insufficient balance!")
# Create an object and test it
account = BankAccount("Ali", 1000)
account.deposit(500)
account.withdraw(300)
account.withdraw(1500)
๐ง Exercise 2: Student Class With Grade
Create a Student
class with:
- name
- grade
- method to print pass/fail (passing if grade โฅ 10)
pythonCopierModifierclass Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def check_pass(self):
if self.grade >= 10:
print(f"{self.name} has passed โ
")
else:
print(f"{self.name} has failed โ")
# Test
student1 = Student("Sara", 14)
student2 = Student("Omar", 7)
student1.check_pass()
student2.check_pass()
๐ Summary
- OOP helps organize code using real-world concepts like “objects” and “actions”.
- A
class
defines the structure, and anobject
is the real version. - Use
__init__()
to initialize object data. - Use methods to define object behavior.
โฌ๏ธ Download Domingo ุชุญู ูู Server 1 โฌ๏ธ Download Domingo ุชุญู ูู Server 2 โฌ๏ธ Download Domingo ุชุญู ูู Server 3Username = abofadi6
Password = 4d141