Oops in Python My Views
Oops in Python My Views
What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of
"objects" which are instances of classes. OOP focuses on organizing code into
reusable chunks with well-defined behaviors.
def accelerate(self):
self.__speed += 5
```
2. **Inheritance**:
- Inheritance allows a class to inherit attributes and methods from another
class.
- This enables code reuse and hierarchical relationships between classes.
Example:
```python
class ElectricCar(Car):
def __init__(self, make, model, battery_capacity):
super().__init__(make, model)
self.battery_capacity = battery_capacity
```
3. **Polymorphism**:
- Polymorphism allows objects to be treated as instances of their parent class,
with different behaviors.
- It can be achieved through method overriding.
Example:
```python
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Bark"
class Cat(Animal):
def make_sound(self):
return "Meow"
```
4. **Abstraction**:
- Abstraction hides the complexity of the system and exposes only the essential
features.
- It allows you to focus on higher-level functionality and reduces complexity.
Example:
```python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
```
Conclusion:
OOP in Python is a powerful way to structure your programs. It encourages modular,
reusable, and maintainable code. Start by creating simple classes and gradually
apply OOP principles to more complex projects.