Say we want to be able to verify that classes we define always have an __info__()
method. We can accomplish that by defining a suitable metaclass and defining any new class that should be checked with a reference to this metaclass. Look at the following example code (also available as metaclassexample.py
):
Chapter7/metaclassexample.py
class hasinfo(type): def __new__(metaclass, classname, baseclasses, classdict): if len(baseclasses) and not '__info__' in classdict: raise TypeError('does not have __info__') return type.__new__(metaclass, classname, baseclasses, classdict) class withinfo(metaclass=hasinfo): pass class correct(withinfo): def __info__(self): pass class incorrect(withinfo): pass
This will raise an exception for the incorrect
class, but not for the correct
class.