Everything in Python is Object-Oriented
Example:
a = 2 # 'a' is an object of integer type
Similarly:
roll = [1, 2, 3, 4]
roll.append(5) # list method
roll.pop() # remove last element
Here, roll is an object of the list class.
π§± What is a Class?
A class is a blueprint. It has:
- Data / Properties β Variables
- Functions / Behaviors β Methods
Example (Structure only):
class Human:
name
age
phone_no
def demo():
pass
- Class names should be in PascalCase β
ThisIsClass - Variable and method names should be in snake_case β
this_is_variable
π‘ OOP Benefits
- β Reusable code
- β No global variables required
- β Organized and modular code
- β Easier debugging
- β Data protection via encapsulation
π Procedural vs Object-Oriented (OOP)
𧨠Non-OOP Example (Risky!):
balance = 100
def withdraw(amount):
global balance
balance -= amount
β
OOP Version (Cleaner and Safer):
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
self.balance -= amount
# Usage
account1 = BankAccount(100)
account2 = BankAccount(200)
account1.withdraw(50) # Only affects account1
π§ Class with Constructor (__init__())
A special method called when the object is created.
Example:
class Atm:
def __init__(self):
print("ATM object created")
Note:
- It's spelled
__init__, not__int__ - Called automatically when an object is instantiated
π __init__() is a Magic Method
Magic methods in Python have double underscores: __method__.
You cannot skip __init__() if you want to initialize object attributes.
π½ OOP Analogy β Like a Recipe!
| OOP Concept | Cooking Analogy |
|---|---|
| Class | Recipe |
| Object | Cooked Dish |
| Instantiation | Cooking |
| Attributes | Spice Level, Garnish |
| Methods | Cooking Instructions |
π Custom Class Example: Dish
Define:
class Dish:
def __init__(self, name, spice_level, garnish):
self.name = name
self.spice_level = spice_level
self.garnish = garnish
def serve(self):
print(f"Serving {self.name} with {self.spice_level} spice and {self.garnish} garnish.")
Create objects:
dish1 = Dish("Curry", "Medium", "Cilantro")
dish2 = Dish("Curry", "Spicy", "Mint Leaves")
dish1.serve()
dish2.serve()
Output:
Serving Curry with Medium spice and Cilantro garnish.
Serving Curry with Spicy spice and Mint Leaves garnish.
π What is self?
- Refers to the current object instance.
- Always required as the first parameter in instance methods.
Example:
self.name = name # means "this objectβs name = the given name"
𧬠Inheritance (Optional but Powerful)
Allows a class to inherit properties and methods from another.
class Dish:
def __init__(self, name):
self.name = name
class SweetDish(Dish):
def serve(self):
print(f"Serving sweet {self.name}")
cake = SweetDish("Cake")
cake.serve() # Output: Serving sweet Cake
π Rest of the part add soon
NB : I collected those from AI Chatbot
Top comments (1)
Carry onβ β β