- 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
Add to BookmarkIntroduction
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
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- 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
Random Blogs
- Robotics & AI – How AI is Powering Modern Robotics
- Internet of Things (IoT) & AI – Smart Devices and AI Working Together
- Generative AI - The Future of Artificial Intelligence
- AI in Cybersecurity: The Future of Digital Protection
- Quantum AI – The Future of AI Powered by Quantum Computing
- Best Platform to Learn Digital Marketing in Free
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- Why to learn Digital Marketing?
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- Top 10 Blogs of Digital Marketing you Must Follow
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Time Series Analysis on Air Passenger Data
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- Store Data Into CSV File Using Python Tkinter GUI Library
- Convert RBG Image to Gray Scale Image Using CV2
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- 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