Python - Classes
In Python, metaclasses are a powerful but advanced feature that allows you to customize the creation and behavior of classes. A metaclass is a class of a class, responsible for defining how classes are created, their attributes, and their methods. Metaclasses are often used to enforce coding standards, perform automatic code generation, or add custom behaviors to classes at the time of creation.
# Metaclass example
class MetaClass(type):
def __new__(cls, name, bases, dct):
# Adding a new attribute to the class
dct['meta_attribute'] = 'This is a meta attribute'
# Creating the class using the type constructor
return super().__new__(cls, name, bases, dct)
# Using the metaclass to create a class
class MyClass(metaclass=MetaClass):
def __init__(self, value):
self.value = value
# Creating an object of the class
obj = MyClass(value=42)
# Accessing both class and meta attributes
class_attribute = obj.value
meta_attribute = obj.meta_attribute
# Displaying the results
print(f"Class attribute: {class_attribute}")
print(f"Meta attribute: {meta_attribute}")
In this example, the MetaClass
is a custom metaclass derived from the built-in type
. The __new__
method of the metaclass is overridden to add a new attribute (meta_attribute
) to any class created with this metaclass. The MyClass
class is created using the MetaClass
as its metaclass, and the metaclass adds the meta_attribute
to instances of MyClass
.
Output:
Class attribute: 42 Meta attribute: This is a meta attribute