Python Metaclass __new__() Method
Last Updated :
21 Mar, 2024
In Python, metaclasses provide a powerful way to customize the creation of classes. One essential method in metaclasses is __new__, which is responsible for creating a new instance of a class before __init__ is called. Understanding the return value of __new__ in metaclasses is crucial for implementing advanced class customization.
What is Python Metaclass __new__() Method?
In a metaclass, the __new__ method is responsible for creating a new instance of the class. The return value of this method determines what object will be passed to the __init__ method. By default, __new__ returns an instance of the class, but it can be customized to alter the creation process.
Syntax
class Meta(type):
def __new__(cls, name, bases, dct):
# Customization logic here
instance = super().__new__(cls, name, bases, dct)
return instance
- cls: The metaclass itself.
- name: The name of the class being created.
- bases: The base classes of the class being created.
- dct: A dictionary containing the class attributes.
Metaclass __new__() Method in Python
Below, are the example of Python Metaclass __new__ usage in Python:
Example 1: Altering Class Name
In this example, below Python code, a metaclass `CustomMeta` is defined, overriding the `__new__` method to prepend the class name with 'Custom'. The class `MyClass` is then created using this metaclass, resulting in the output of the modified class name, 'CustomMyClass'.
Python3
class CustomMeta(type):
def __new__(cls, name, bases, dct):
# Adding 'Custom' prefix to class name
name = 'Custom' + name
instance = super().__new__(cls, name, bases, dct)
return instance
class MyClass(metaclass=CustomMeta):
pass
print(MyClass.__name__)
Example 2: Singleton Metaclass
In this example, below Python code, a metaclass `SingletonMeta` is used to enforce the Singleton pattern. The `__new__` method ensures that only one instance of the class `SingletonClass` is created, and the subsequent objects `obj1` and `obj2` are identical, as indicated by the output `True` when comparing their identity using the `is` operator.
Python3
class SingletonMeta(type):
_instances = {}
def __new__(cls, name, bases, dct):
if name not in cls._instances:
cls._instances[name] = super().__new__(cls, name, bases, dct)
return cls._instances[name]
class SingletonClass(metaclass=SingletonMeta):
pass
obj1 = SingletonClass()
obj2 = SingletonClass()
print(obj1 is obj2)
Example 3: Attribute Validation
In this example, below Python code, the metaclass ValidationMeta is designed to validate that the attribute 'value' in classes using this metaclass is always an integer. When attempting to create an instance of the IntegerClass with a non-integer value, such as 'not_an_integer', a TypeError is raised, leading to the output of the error message "'value' must be an integer."
Python3
class ValidationMeta(type):
def __new__(cls, name, bases, dct):
# Ensure 'value' attribute is always an integer
if 'value' in dct and not isinstance(dct['value'], int):
raise TypeError("'value' must be an integer.")
instance = super().__new__(cls, name, bases, dct)
return instance
class IntegerClass(metaclass=ValidationMeta):
value = 42
try:
invalid_obj = IntegerClass(value='not_an_integer')
except TypeError as e:
print(e)
OutputIntegerClass() takes no arguments
Conclusion
In conclusion, Understanding the return value of __new__ in Python metaclasses allows developers to implement advanced class customization. Whether it's altering class names, enforcing singleton patterns, or validating attributes, the power of metaclasses can be harnessed through the careful customization of the __new__ method. By using the examples provided, developers can explore and apply these concepts to create more flexible and robust class structures in their Python programs.
Similar Reads
classmethod() in Python
The classmethod() is an inbuilt function in Python, which returns a class method for a given function. This means that classmethod() is a built-in Python function that transforms a regular method into a class method. When a method is defined using the @classmethod decorator (which internally calls c
8 min read
Call Parent class method - Python
In object-oriented programming in Python, the child class will inherit all the properties and methods of the parent class when the child class inherits the parent class. But there may be some cases when the child class has to call the methods of the parent class directly. Python has an easy and effe
5 min read
Python MetaClasses
The key concept of python is objects. Almost everything in python is an object, which includes functions and as well as classes. As a result, functions and classes can be passed as arguments, can exist as an instance, and so on. Above all, the concept of objects let the classes in generating other c
9 min read
Python | getattr() method
The getattr() method in Python returns the value of a named attribute of an object. If the attribute is not found then it returns the default value provided. If no default is given and the attribute does not exist then it raises an AttributeError.Python getattr() Method SyntaxSyntax : getattr(obj, k
3 min read
Python List methods
Python list methods are built-in functions that allow us to perform various operations on lists, such as adding, removing, or modifying elements. In this article, weâll explore all Python list methods with a simple example.List MethodsLet's look at different list methods in Python:append(): Adds an
3 min read
Python - __lt__ magic method
Python __lt__ magic method is one magic method that is used to define or implement the functionality of the less than operator "<" , it returns a boolean value according to the condition i.e. it returns true if a<b where a and b are the objects of the class. Python __lt__ magic method Syntax S
2 min read
Python __add__() magic method
Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator "+" in Python. Python __add__() Syntax Syntax: obj1.__add__(self, obj2) obj1: First object to add in the second object.obj2
1 min read
python class keyword
In Python, class keyword is used to create a class, which acts as a blueprint for creating objects. A class contains attributes and methods that define the characteristics of the objects created from it. This allows us to model real-world entities as objects with their own properties and behaviors.S
1 min read
Extend Class Method in Python
In Python, class methods are functions that are bound to the class rather than the instance of the class. This means they receive the class (cls) as the first argument instead of the instance (self). Extending a class method refers to enhancing or customizing the behavior of an inherited class metho
3 min read
Python __len__() magic method
Python __len__ is one of the various magic methods in Python programming language, it is basically used to implement the len() function in Python because whenever we call the len() function then internally __len__ magic method is called. It finally returns an integer value that is greater than or eq
2 min read