OOP_in_Python_Skillzam
OOP_in_Python_Skillzam
1. What is OOP?
OOP is a programming paradigm based on objects containing attributes (data) and methods (functions).
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!')
Example:
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def show_info(self):
print(f'Student: {self.name}, Grade: {self.grade}')
s1 = Student('Alice', 'A')
s1.show_info()
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
Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance
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!')
Example:
class Data:
def __init__(self, dataset):
self.dataset = dataset
def get_mean(self):
return sum(self.dataset) / len(self.dataset)