OOPs Concepts in Python:
Here's a breakdown of the key OOPs concepts in Python, along with examples:
Class:
● A blueprint for creating objects, defining their attributes (data) and methods (functions).
● Think of it as a template describing properties and behaviors common to a group of similar
things.
● Example:
Python
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
my_dog = Dog("Buddy", "Golden Retriever")
Objects:
● Individual instances of a class, each with their own unique data (attributes).
● They represent specific entities and can interact with other objects.
● Example:
Python
my_dog.bark() # Output: Woof!
Polymorphism:
● The ability of objects of different classes to respond differently to the same method call.
● Achieved through method overriding in subclasses or using protocols like duck typing.
● Example:
Python
class Animal:
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print("Woof!")
class Cat(Animal):
def make_sound(self):
print("Meow!")
animals = [Dog(), Cat()]
for animal in animals:
animal.make_sound() # Output: Woof! Meow!
Encapsulation:
● Bundling data and methods together within an object, restricting direct access to internal
data.
● Promotes data security and modularity by controlling how data is modified.
● Achieved using private attributes and methods (prefixed with _).
● Example:
Python
class Car:
def __init__(self, model, year):
self._model = model
self.year = year
def get_model(self):
return self._model
my_car = Car("Tesla Model S", 2023)
# my_car._model will be inaccessible directly
print(my_car.get_model()) # Output: Tesla Model S
Inheritance:
● Allows creating new classes (subclasses) that inherit attributes and methods from existing
classes (superclasses).
● Promotes code reuse and reduces complexity by leveraging existing functionality.
● Achieved using the class Subclass(Superclass): syntax.
● Example:
Python
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
class ElectricCar(Vehicle):
def charge(self):
print("Charging...")
my_electric_car = ElectricCar("Tesla", "Model 3")
print(my_electric_car.make) # Output: Tesla
my_electric_car.charge() # Output: Charging...
Data Abstraction:
● Hiding unnecessary details and exposing only essential information about an object's data.
● Simplifies object interaction and promotes modularity by focusing on relevant information.
● Achieved using methods to access and manipulate data instead of directly accessing
attributes.
● Example:
Python
class User:
def __init__(self, username, email):
self._username = username
self._email = email
def get_username(self):
return self._username
# No need to expose the email directly
# Use getter method for controlled access
print(my_user.get_username()) # Output: johndoe
Remember, these are just basic explanations. Feel free to ask for further clarification on any
specific aspect or if you have any additional questions!