Learn all about Object Oriented Programming in Python | learn oops
1. Classes and Objects
A class is like a blueprint for creating objects. An object is an instance of a class. In OOP, classes define the structure (attributes) and behavior (methods) of objects.
class Car:
def __init__(self, brand, model):
self.brand = brand # attribute
self.model = model # attribute
def display_info(self): # method
print(f"Car Brand: {self.brand}, Model: {self.model}")
# Creating an object of the class Car
my_car = Car("Toyota", "Corolla")
my_car.display_info() # Output: Car Brand: Toyota, Model: Corolla
2. Scope Resolution
In Python, the scope resolution operator ( ::
in some languages) is replaced by dot notation ( .
). It is used to refer to a specific method or attribute in a class.
class Student:
school = "ABC School" # Class variable
def __init__(self, name):
self.name = name # Instance variable
def display_school(self):
print(Student.school) # Using scope resolution via class name
# Accessing class attribute
student1 = Student("John")
student1.display_school() # Output: ABC School
3. Inheritance
Inheritance allows one class (child) to inherit properties and behavior (methods) from another class (parent). This helps in code reusability.
class Vehicle:
def __init__(self, brand):
self.brand = brand
def show_brand(self):
print(f"Brand: {self.brand}")
# Car inherits Vehicle
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand) # Using the parent class constructor
self.model = model
def show_model(self):
print(f"Model: {self.model}")
my_car = Car("Honda", "Civic")
my_car.show_brand() # Output: Brand: Honda
my_car.show_model() # Output: Model: Civic
4. Virtual Base Class (Multiple Inheritance)
In Python, multiple inheritance means that a class can inherit from more than one base class. When there are multiple inheritance paths, virtual base classes ensure that the base class is not duplicated in the hierarchy.
class A:
def show(self):
print("Class A")
class B(A):
def show(self):
print("Class B")
class C(A):
def show(self):
print("Class C")
# D inherits from both B and C
class D(B, C):
pass
d = D()
d.show() # Output: Class B (Because of MRO)
print(D.mro()) # Output: [D, B, C, A, object] (MRO shows the order)
5. Diamond Problem
The diamond problem arises in multiple inheritance when a child class inherits from two classes that share a common ancestor, leading to ambiguity about which method to use. Python resolves it using MRO (Method Resolution Order).
6. Virtual Function
Python doesn’t have explicit "virtual functions" like C++, but you can achieve similar functionality using method overriding. When a child class overrides a method of the parent class, that overridden method gets called instead of the parent method.
class Animal:
def sound(self):
print("Animal makes a sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
# Overridden method gets called
dog = Dog()
dog.sound() # Output: Dog barks
7. Friend Function
Python doesn’t have an explicit concept of a "friend function" like in C++. However, you can achieve similar functionality by allowing external functions to access private data (which is not recommended but possible).
class MyClass:
def __init__(self, name):
self.__name = name # Private variable
def get_name(self):
return self.__name # A public method accessing the private variable
# Simulating "friend-like" behavior
def display_friend_name(obj):
return obj.get_name()
obj = MyClass("Nikhil")
print(display_friend_name(obj)) # Output: Nikhil
8. Ambiguity
In multiple inheritance, if two parent classes have methods with the same name, it creates ambiguity as to which method the child class should use. This is resolved by Python using MRO.
class Parent1:
def greet(self):
print("Hello from Parent 1")
class Parent2:
def greet(self):
print("Hello from Parent 2")
class Child(Parent1, Parent2):
pass
child = Child()
child.greet() # Output: Hello from Parent 1 (MRO selects the first parent)
9. Polymorphism
Polymorphism allows functions to operate on objects of different classes, treating them as if they are of the same type. This is achieved using method overriding or by using *args
or **kwargs
to accept a variable number of arguments.
class Bird:
def fly(self):
print("Bird is flying")
class Sparrow(Bird):
def fly(self):
print("Sparrow is flying")
class Eagle(Bird):
def fly(self):
print("Eagle is flying")
# Using polymorphism
def show_fly(bird):
bird.fly()
sparrow = Sparrow()
eagle = Eagle()
show_fly(sparrow) # Output: Sparrow is flying
show_fly(eagle) # Output: Eagle is flying
10. Encapsulation
Encapsulation is the concept of bundling data (attributes) and methods that operate on that data into a single unit, or class. It also involves restricting access to certain attributes to keep them safe from external interference.
class Person:
def __init__(self, name, age):
self.__name = name # Private attribute
self.age = age # Public attribute
def get_name(self):
return self.__name # Getter method to access private attribute
p = Person("Alice", 30)
print(p.get_name()) # Output: Alice
Summary
- Classes and Objects: A class is a blueprint; objects are instances of that class.
- Scope Resolution: Python uses dot notation to access methods and attributes.
- Inheritance: A class can inherit properties from another class.
- Virtual Base Class: Multiple inheritance is handled using MRO (Method Resolution Order).
- Diamond Problem: Solved using MRO in Python.
- Virtual Function: Achieved through method overriding.
- Friend Function: Simulated using public methods.
- Ambiguity: Resolved using MRO.
- Polymorphism: Allows methods to work on objects of different types.
- Encapsulation: Bundles data and methods while restricting access to certain attributes.
Comments
Post a Comment