OOPS CONCEPT IN PYTHON
Python's core idea of object-oriented programming enables programmers to create modular, scalable, and maintainable applications. Programmers may take full advantage of Python's OOP features to create sophisticated and effective solutions to challenging issues by comprehending the fundamental OOP concepts of classes, objects, inheritance, encapsulation, polymorphism, and abstraction. More detailed about it...
What is object oriented programming in python
Python object-oriented programming, or OOPs, is a paradigm for writing code that makes use of classes and objects. It attempts to incorporate into the programming real-world concepts like encapsulation, inheritance, and polymorphisms. Binding data and functions that cooperate as a single unit is the fundamental idea behind object-oriented programming (OOPs) or oops principles in Python. This ensures that no other section of the code can access the data.
Python OOPs Concepts:
Python OOPs Concepts:
- Python class
- Python Objects
- Python Polymorphism
- Python Encapsulation
- Python Inheritance
- Python Data Abstraction
1) Python classes :
In Python, a class is a blueprint for creating objects (instances). It defines the structure and behavior (properties and methods) that the created objects will have. A class allows you to group data (attributes) and functions (methods) together, enabling object-oriented programming (OOP), which promotes code reuse and organization.
Key Points:
- A class defines the attributes (variables) and behaviors (methods) that the objects created from the class will have.
- An object is an instance of a class, and it holds the actual data.
- Methods inside a class operate on the object's attributes.
Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f"This car is a {self.brand} {self.model}.")
# Creating an object (instance) of the Car class
my_car = Car("Toyota", "Corolla")
my_car.display_info()
Explanation:
`class Car`: Defines a class named `Car`.
`__init__`: A special method called a constructor, which initializes the object’s attributes (like `brand` and `model`).
`display_info`: A method that prints the car’s information.
This structure allows Python to follow the OOP paradigm, making code more modular and reusable.
2) Python Objects
In Python, an object is an instance of a class. Everything in Python is considered an object, including integers, strings, lists, functions, and more. Objects are created from classes, which define a blueprint for the objects, specifying their properties (attributes) and behaviors (methods).
Key Concepts:
1. Class: A blueprint for creating objects.
class Dog:
def __init__(self, name):
self.name = name
2. Object: An instance of a class.
my_dog = Dog("Buddy")
# 'my_dog' is an object of class 'Dog'
3. Attributes: Variables that hold data related to the object.
print(my_dog.name) # Output: Buddy
4. Methods: Functions defined inside a class that describe the behaviors of the object.
class Dog:
def bark(self):
print("Woof!")
my_dog.bark() # Output: Woof!
3) Python Polymorphism
Polymorphism in Python refers to the ability of different objects to respond to the same method or function in different ways. This is an important concept in object-oriented programming that promotes flexibility and reusability of code.
Key Concepts of Polymorphism:
1. Method Overriding: Different classes can implement the same method in their own way.
2. Function and Method Polymorphism: A single function can work with different types of objects.
Example of Polymorphism:
1. Polymorphism with Class Methods:
Different classes can have methods with the same name, and Python allows you to call these methods interchangeably.
class Dog:
def sound(self):
return "Bark"
class Cat:
def sound(self):
return "Meow"
def animal_sound(animal):
print(animal.sound())
dog = Dog()
cat = Cat()
animal_sound(dog) # Output: Bark
animal_sound(cat) # Output: Meow
2. Polymorphism with Inheritance (Method Overriding):
When a child class overrides a method from the parent class, it demonstrates polymorphism because the method behaves differently depending on the object.
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
animals = [Dog(), Cat(), Animal()]
for animal in animals:
print(animal.sound())
# Output:
# Bark
# Meow
# Some sound
Benefits of Polymorphism:
- Code Reusability: Write generic functions and methods that can work with different types of objects.
- Flexibility: Extend the behavior of functions or methods with new classes without modifying existing code.
4) Python Encapsulation
Encapsulation in Python is one of the fundamental concepts of object-oriented programming (OOP). It refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit or class, while restricting access to some of the object's components to protect the integrity of the data. Encapsulation allows you to hide the internal details of an object and expose only what is necessary, promoting better data security and code maintenance.
Key Concepts of Encapsulation:
1. Private Attributes: By using a double underscore (`__`), you can make an attribute or method private, restricting access to it from outside the class.
2. Getter and Setter Methods: These are methods that allow controlled access to private attributes.
Example of Encapsulation:
1. Private Attributes:
In the example below, the `__balance` attribute is private and cannot be accessed directly outside the class.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient balance")
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
account.withdraw(300)
print(account.get_balance()) # Output: 1200
# Trying to access the private attribute directly
# print(account.__balance) # This will raise an AttributeError
2. Getter and Setter Methods:
Encapsulation also involves controlling how attributes are accessed and modified using methods.
class Employee:
def __init__(self, name, salary):
self.__name = name # Private attribute
self.__salary = salary # Private attribute
# Getter method for name
def get_name(self):
return self.__name
# Setter method for name
def set_name(self, new_name):
self.__name = new_name
# Getter method for salary
def get_salary(self):
return self.__salary
# Setter method for salary
def set_salary(self, new_salary):
if new_salary > 0:
self.__salary = new_salary
else:
print("Salary must be positive")
# Create an instance of Employee
emp = Employee("John", 50000)
# Accessing and modifying private attributes using getter and setter methods
print(emp.get_name()) # Output: John
emp.set_name("Jane")
print(emp.get_name()) # Output: Jane
print(emp.get_salary()) # Output: 50000
emp.set_salary(60000)
print(emp.get_salary()) # Output: 60000
Benefits of Encapsulation:
- Data Protection: Prevents unauthorized access or modification of object attributes.
- Controlled Access: You can specify exactly how attributes can be accessed or changed.
- Modularity: Makes code easier to maintain and modify.
Encapsulation is crucial in maintaining the integrity of an object's data by allowing controlled access and modification through public methods.
5) Python Inheritance
inheritance in Python is a fundamental concept of object-oriented programming (OOP) that allows a class (called a subclass or child class) to inherit attributes and methods from another class (called a superclass*or parent class). This promotes code reusability and establishes a hierarchical relationship between classes.
Key Concepts of Inheritance:
1. Single Inheritance: A subclass inherits from one superclass.
2. Multiple Inheritance: A subclass can inherit from multiple superclasses.
3. Multilevel Inheritance: A subclass inherits from a superclass, which in turn inherits from another superclass.
4. Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.
Example of Inheritance:
1. Single Inheritance:
class Animal: # Superclass
def speak(self):
return "Animal speaks"
class Dog(Animal): # Subclass
def bark(self):
return "Woof!"
# Creating an object of the Dog class
dog = Dog()
print(dog.speak()) # Output: Animal speaks
print(dog.bark()) # Output: Woof!
2. Multiple Inheritance:
class Swimmer:
def swim(self):
return "Swimming"
class Walker:
def walk(self):
return "Walking"
class Duck(Swimmer, Walker): # Inherits from both Swimmer and Walker
def quack(self):
return "Quack!"
# Creating an object of the Duck class
duck = Duck()
print(duck.swim()) # Output: Swimming
print(duck.walk()) # Output: Walking
print(duck.quack()) # Output: Quack!
```
3. Multilevel Inheritance:
class Animal: # Superclass
def speak(self):
return "Animal speaks"
class Dog(Animal): # Intermediate subclass
def bark(self):
return "Woof!"
class Puppy(Dog): # Subclass of Dog
def weep(self):
return "Whimper!"
# Creating an object of the Puppy class
puppy = Puppy()
print(puppy.speak()) # Output: Animal speaks
print(puppy.bark()) # Output: Woof!
print(puppy.weep()) # Output: Whimper!
4. Hierarchical Inheritance:
class Animal: # Superclass
def speak(self):
return "Animal speaks"
class Dog(Animal): # Subclass 1
def bark(self):
return "Woof!"
class Cat(Animal): # Subclass 2
def meow(self):
return "Meow!"
# Creating objects of Dog and Cat classes
dog = Dog()
cat = Cat()
print(dog.speak()) # Output: Animal speaks
print(cat.speak()) # Output: Animal speaks
print(dog.bark()) # Output: Woof!
print(cat.meow()) # Output: Meow!
```
Benefits of Inheritance:
- Code Reusability: Inherits attributes and methods from the parent class, reducing code duplication.
- Logical Structure: Establishes a natural hierarchy, making code easier to understand.
- Method Overriding: Allows subclasses to provide specific implementations of methods defined in the parent class.
Method Overriding:
A subclass can override a method of the superclass to provide its own implementation.
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal):
def speak(self): # Overriding the speak method
return "Woof!"
dog = Dog()
print(dog.speak()) # Output: Woof!
Inheritance is a powerful feature in Python that promotes a clean and manageable code structure.
6) Python Data Abstraction
Data Abstraction in Python is the process of hiding the implementation details of a class and exposing only the necessary functionality. It allows the user to focus on **what** an object does instead of how it does it. By providing a clean interface, abstraction simplifies the complexity of working with objects.
In Python, abstraction can be achieved using:
1. Abstract Classes
2. Abstract Methods
Abstract Classes
An abstract class is a class that cannot be instantiated on its own and typically contains one ormore abstract methods. An abstract method is defined in the base class but must be implemented by its subclasses.
Python provides the `abc` module, which allows you to define abstract classes and methods using the `ABC` (Abstract Base Class) and `@abstractmethod` decorators.
Example of Data Abstraction:
from abc import ABC, abstractmethod
# Abstract Class
class Shape(ABC):
@abstractmethod
def area(self):
pass # Abstract method, to be implemented by subclasses
@abstractmethod
def perimeter(self):
pass # Another abstract method
# Subclass (Concrete Class) of the abstract class
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
# Subclass (Concrete Class) of the abstract class
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * (self.radius ** 2)
def perimeter(self):
return 2 * 3.14 * self.radius
# Objects of concrete classes
rect = Rectangle(4, 6)
print("Rectangle Area:", rect.area()) # Output: Rectangle Area: 24
print("Rectangle Perimeter:", rect.perimeter()) # Output: Rectangle Perimeter: 20
circle = Circle(5)
print("Circle Area:", circle.area()) # Output: Circle Area: 78.5
print("Circle Perimeter:", circle.perimeter()) # Output: Circle Perimeter: 31.400000000000002
Key Concepts:
1. Abstract Class: A class that cannot be instantiated on its own but serves as a blueprint for other classes.
- In the example, `Shape` is an abstract class.
2. Abstract Method: A method that is declared but not implemented in the abstract class. It must be implemented in subclasses.
- In the example, `area()` and `perimeter()` are abstract methods that are implemented in `Rectangle` and `Circle`.
3. Concrete Class: A class that implements all abstract methods and can be instantiated.
- In the example, `Rectangle` and `Circle` are concrete classes.
Benefits of Data Abstraction:
- Simplifies Complexity: Users of the class do not need to understand the underlying implementation, only how to use the class.
- Enhances Security: By hiding the internal details, it prevents unintended interference or modification.
- Promotes Reusability Abstract classes can be extended by different classes, making code reusable.
When to Use Data Abstraction:
- When you have multiple classes that share similar methods but have different implementations.
- To create a common interface for a group of subclasses.
0 Comments