- 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
typein 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
typeas the metaclass for all classes.
Analogy:
- Objects are instances of a class → A dog is an instance of the
Animalclass. - Classes are instances of a metaclass →
Animalis an instance of thetypemetaclass.
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 SchoolBreaking 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: IndiaHow 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 uppercaseSingleton 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
- JavaScript Interview Questions for 5+ Years Experience
- JavaScript Interview Questions for 2–5 Years Experience
- JavaScript Interview Questions for 1–2 Years Experience
- JavaScript Interview Questions for 0–1 Year Experience
- JavaScript Interview Questions For Fresher
- SQL Interview Questions for 5+ Years Experience
- 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
Random Blogs
- Python Challenging Programming Exercises Part 2
- How Multimodal Generative AI Will Change Content Creation Forever
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- Generative AI - The Future of Artificial Intelligence
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Convert RBG Image to Gray Scale Image Using CV2
- The Ultimate Guide to Data Science: Everything You Need to Know
- 15 Amazing Keyword Research Tools You Should Explore
- Python Challenging Programming Exercises Part 3
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- Robotics & AI – How AI is Powering Modern Robotics
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- AI & Space Exploration – AI’s Role in Deep Space Missions and Planetary Research
- Important Mistakes to Avoid While Advertising on Facebook
- Grow your business with Facebook Marketing
Datasets for Machine Learning
- Awesome-ChatGPT-Prompts
- 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


