how to learn OOP
how to learn OOP
What is OOP?
Object-Oriented Programming is a programming paradigm based on the concept of
"objects," which can contain data (attributes) and code (methods).
Key Principles of OOP:
o Encapsulation: Bundling data and methods together.
o Abstraction: Hiding implementation details and exposing only the essentials.
o Inheritance: Creating new classes from existing ones to promote code reuse.
o Polymorphism: Allowing objects to be treated as instances of their parent
class.
python
Copier le code
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f"{self.brand} {self.model}")
2. Encapsulation
Restrict access to certain parts of the object.
python
Copier le code
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
def get_balance(self):
return self.__balance
account = BankAccount(100)
account.deposit(50)
print(account.get_balance()) # Output: 150
3. Inheritance
python
Copier le code
class Animal:
def speak(self):
print("I make a sound.")
class Dog(Animal):
def speak(self):
print("Woof!")
my_dog = Dog()
my_dog.speak() # Output: Woof!
4. Polymorphism
python
Copier le code
class Shape:
def area(self):
pass
class Circle(Shape):
def area(self):
print("Area of Circle")
class Square(Shape):
def area(self):
print("Area of Square")
Hands-on practice is the best way to learn. Start with small projects:
Basic Projects:
o Create a library management system with books as objects.
o Build a car rental service with inheritance for different vehicle types.
Advanced Projects:
o Develop a simple game like Tic-Tac-Toe with player objects.
o Create a shopping cart application using classes and objects.
Join communities on platforms like GitHub, Stack Overflow, or Reddit to share your
code and learn from others.