Object-Oriented Programming (OOP) in Python - Skillzam
Why is OOP Important for Data Science?
OOP helps in data science by:
- Organizing Code
- Reusability
- Scalability
It allows structuring complex models efficiently.
1. What is OOP?
OOP is a programming paradigm based on objects containing attributes (data) and methods (functions).
2. Classes and Objects
A class is a blueprint, and an object is an instance of that class.
Example:
class Car:
def __init__(self, brand, color):
self.brand = brand
self.color = color
def drive(self):
print(f'The {self.color} {self.brand} is driving!')
my_car = Car('Tesla', 'Red')
print(my_car.brand)
my_car.drive()
3. The __init__ Method
This special method initializes objects.
Example:
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
Skillzam - Teaching Python with Ease
Object-Oriented Programming (OOP) in Python - Skillzam
def show_info(self):
print(f'Student: {self.name}, Grade: {self.grade}')
s1 = Student('Alice', 'A')
s1.show_info()
4. The self Keyword
The self keyword refers to the current instance of the class and allows access to its attributes and methods.
5. Inheritance
Inheritance allows a child class to inherit attributes and methods from a parent class.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print('Some sound...')
class Dog(Animal):
def speak(self):
print(f'{self.name} says Woof!')
dog1 = Dog('Buddy')
dog1.speak()
6. Encapsulation
Encapsulation restricts direct access to data.
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance
Skillzam - Teaching Python with Ease
Object-Oriented Programming (OOP) in Python - Skillzam
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
acc = BankAccount(1000)
acc.deposit(500)
print(acc.get_balance())
7. Polymorphism
Polymorphism allows methods with the same name to behave differently in different classes.
Example:
class Bird:
def sound(self):
print('Some bird sound')
class Parrot(Bird):
def sound(self):
print('Parrot says: Squawk!')
class Crow(Bird):
def sound(self):
print('Crow says: Caw!')
for bird in [Parrot(), Crow()]:
bird.sound()
8. OOP in Data Science
OOP is used in data science for:
- Data Modeling (e.g., pandas DataFrame)
- Machine Learning Models (e.g., scikit-learn)
- Encapsulation of ML data
Skillzam - Teaching Python with Ease
Object-Oriented Programming (OOP) in Python - Skillzam
- Reusable ML structures
Example:
class Data:
def __init__(self, dataset):
self.dataset = dataset
def get_mean(self):
return sum(self.dataset) / len(self.dataset)
data = Data([10, 20, 30, 40])
print(data.get_mean())
Skillzam - Teaching Python with Ease