A basic metaclass
Since metaclasses can modify any class attribute, you can do absolutely anything you wish. Before we continue with more advanced metaclasses, let’s create a metaclass that does the following:
- Makes the class inherit
int
- Adds a
lettuce
attribute to the class - Changes the name of the class
First we create the metaclass. After that, we create a class both with and without the metaclass:
# The metaclass definition, note the inheritance of type instead
# of object
>>> class MetaSandwich(type):
... # Notice how the __new__ method has the same arguments
... # as the type function we used earlier?
... def __new__(metaclass, name, bases, namespace):
... name = 'SandwichCreatedByMeta'
... bases = (int,) + bases
... namespace['lettuce'] = 1
... return type.__new__(metaclass, name, bases, namespace)
First, the regular Sandwich:
>>> class Sandwich...