Key Features of OOP
- 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.
- 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.
- 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.
- 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.
- Dynamic Typing & Duck-typing
- First-class Classes & Methods
- Multiple Inheritance (using MRO & C3 linearization methods)
- Mixins
- Descriptors
- Dynamic Method Addition & Monkey-patching
- Dunder Method Overloading
- Abstract Classes
- Weak References
- Callable Objects
- Exception Handling
- __slots__
- Garbage Collector
New OOP Features in Python 3:
- Class & Property Decorators
- Metaclasses
- 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