Object Oriented Programming in Python | Notes

Key Features of OOP

  1. Encapsulation: Binding Data & methods that operate on data together in a single unit is called Encapsulation. This is achieved through the use of Classes & Objects.
  2. Abstraction: Hiding unnecessary implementation details from the outer world and showing only important usable details of an object is called Abstraction. This is achieved through access modifiers – public, private & protected.
  3. Inheritance: A Class can inherit properties & methods from another class using Inheritance. The subclass can inherit properties and methods from a class (base class) and then either add more properties/methods or redefine existing methods of the base class.
  4. Polymorphism: The term “Polymorphism” means many forms. In OOP, it refers to superclass & subclass having the same method names but different implementations or parameters.

Unique OOP Features in Python

These are the OOP features provided by Python, provided by only a few other or no other programming languages.

  1. Dynamic Typing & Duck-typing
  2. First-class Classes  & Methods
  3. Multiple Inheritance (using MRO & C3 linearization methods)
  4. Mixins
  5. Descriptors
  6. Dynamic Method Addition & Monkey-patching
  7. Dunder Method Overloading
  8. Abstract Classes
  9. Weak References
  10. Callable Objects
  11. Exception Handling
  12. __slots__
  13. Garbage Collector

New OOP Features in Python 3:

  1. Class & Property Decorators
  2. Metaclasses
  3. Coroutines & Generators

Python Syntax for Object-Oriented Programming

Class Declaration

class ClassName:
    #class body

Access Specifiers

class ClassName:
    attribute_name    #Public attribute
    method_name       #Public Method
    _attribute_name   #Protected attribute
    _method_name      #Protected Method
    __attribute_name  #Private attribute
    __method_name     #Private Method

Object Creation / Instantiating a Class

object_name = ClassName(arguments)

Constructor

def __init__(self, parameters):
    #constructor body

Accessing Objects

ObjectName.property
ObjectName.method()

Inheritance

class DerivedClass(BaseClass):
    #class body

Multiple Inheritance

class DerivedClass(BaseClass1, BaseClass2):
    # class body

Calling Parent Class Method

super().method_name(parameters)

Instance Method Declaration

def method_name(self, parameters):
    #method body

Class Method Declaration

@classmethod
def method_name(cls, parameters):
    #method body

Static Method declaration

@staticmethod
def method_name(parameters):
    #method body

Abstract Method

abstract returnType methodName(parameters);

Abstract Class

from abc import ABC, abstractmethod

class ClassName(ABC):
    @abstractmethod
    def method_name(self, parameters):
        # abstract method body

Destructor

def __del__(self):
    #destructor body