0% found this document useful (0 votes)
8 views

Oops in Python My Views

Uploaded by

newel31882
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Oops in Python My Views

Uploaded by

newel31882
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Introduction to Object-Oriented Programming (OOP) in Python

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.

Core Principles of OOP:


1. **Encapsulation**:
- Encapsulation refers to bundling data (attributes) and methods (functions)
that operate on the data into a single unit called a class.
- It also involves restricting access to some of the object's components using
access modifiers (e.g., private, public).
Example:
```python
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
self.__speed = 0 # private attribute

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.

You might also like