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:
type in class creationtype as the metaclass for all classes.Analogy:
Animal class.Animal is an instance of the type metaclass.class MyClass:
pass
print(type(MyClass)) # Output: <class 'type'>type in Class CreationThe type function in Python is both:
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 attributesA 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?
__new__ method is called before the class is created.class_dict) is modified to include country = 'India'.Student.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 uppercaseA 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)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
Sign in to join the discussion and post comments.
Sign inPython for Web Development
Python for Web Development is a comprehensive tutorial series covering the fundamentals of building web applications using Flask and Django. From setting up a project to working with databases, authentication, REST APIs, and deployment on cloud platforms, this series provides a solid foundation for developing secure and scalable web applications.
Python Basics
Python is a powerful, high-level programming language known for its simplicity and versatility. It is widely used in various fields, including web development, data science, artificial intelligence, automation, and more. This tutorial series is designed to take you from the basics of Python to more advanced topics, ensuring a strong foundation in programming.