- Object-Oriented Programming (OOP) in Python
-
Overview
- Introduction to OOP in Python
- Classes and Objects
- Constructors (__init__) and Destructors
- Inheritance (Single, Multiple, Multilevel)
- Polymorphism and Method Overriding
- Encapsulation and Data Hiding
- Abstract Classes and Interfaces
- Static and Class Methods
- Magic/Dunder Methods (__str__, __repr__)
- Metaclasses in Python
- Method Resolution Order (MRO) in Python
Metaclasses in Python
Introduction
In Python, metaclasses define how classes themselves behave. While regular classes define the structure and behavior of objects, metaclasses define the structure and behavior of classes.
In this tutorial, we will cover:
- What is a metaclass?
- The role of
type
in class creation - Creating custom metaclasses
- Practical use cases of metaclasses
1. What is a Metaclass?
- A metaclass is a class that creates classes.
- It controls the creation, modification, and behavior of classes.
- By default, Python uses
type
as the metaclass for all classes.
Analogy:
- Objects are instances of a class → A dog is an instance of the
Animal
class. - Classes are instances of a metaclass →
Animal
is an instance of thetype
metaclass.
class MyClass:
pass
print(type(MyClass)) # Output: <class 'type'>
2. The Role of type
in Class Creation
The type
function in Python is both:
- A constructor that creates new types (metaclass functionality).
- A function that returns the type of an object.
Example: Creating a class dynamically using type
# Creating a class dynamically using type()
Student = type('Student', (), {'school': 'Delhi Public School'})
# Creating an instance
s1 = Student()
print(s1.school) # Output: Delhi Public School
Breaking down type('Student', (), {'school': 'DPS'})
'Student'
→ Name of the class()
→ Tuple of parent classes (empty means no inheritance){'school': 'DPS'}
→ Class attributes
3. Creating Custom Metaclasses
A custom metaclass allows us to modify class creation before the class is instantiated.
class CustomMeta(type):
def __new__(cls, name, bases, class_dict):
print(f"Creating class: {name}")
class_dict['country'] = 'India' # Adding a default attribute
return super().__new__(cls, name, bases, class_dict)
# Using the metaclass
class Student(metaclass=CustomMeta):
def __init__(self, name):
self.name = name
# Creating an object
s1 = Student("Amit")
print(s1.country) # Output: India
How it works?
- The
__new__
method is called before the class is created. - The class dictionary (
class_dict
) is modified to includecountry = 'India'
. - The modified class is returned and used as
Student
.
4. Practical Use Cases of Metaclasses
Enforcing Coding Standards
You can use metaclasses to ensure all class attributes are uppercase.
class UpperCaseMeta(type):
def __new__(cls, name, bases, class_dict):
for attr_name in class_dict:
if not attr_name.isupper() and not attr_name.startswith('__'):
raise TypeError(f"Attribute '{attr_name}' must be uppercase")
return super().__new__(cls, name, bases, class_dict)
class Config(metaclass=UpperCaseMeta):
API_KEY = "12345"
DEBUG_MODE = True # This will raise an error!
# Output: TypeError: Attribute 'DEBUG_MODE' must be uppercase
Singleton Pattern Using Metaclasses
A singleton ensures that only one instance of a class exists.
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Database(metaclass=SingletonMeta):
pass
db1 = Database()
db2 = Database()
print(db1 is db2) # Output: True (Same instance)
5. Summary
Metaclasses define how classes are createdtype
is the default metaclass in Python
Custom metaclasses allow modifying class behavior before instantiation
Use cases include enforcing coding standards, singletons, and dynamic modifications
Prepare for Interview
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
Random Blogs
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Google’s Core Update in May 2020: What You Need to Know
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- Why to learn Digital Marketing?
- Extract RGB Color From a Image Using CV2
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- Understanding OLTP vs OLAP Databases: How SQL Handles Query Optimization
- Python Challenging Programming Exercises Part 2
- Government Datasets from 50 Countries for Machine Learning Training
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- Time Series Analysis on Air Passenger Data
- Quantum AI – The Future of AI Powered by Quantum Computing
- What is YII? and How to Install it?
- Data Analytics: The Power of Data-Driven Decision Making
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset