Exercises
The most important point of this chapter is to teach you how metaclasses work internally: a metaclass is just a class that creates a class, which, in turn, is created by another metaclass (eventually ending up recursively at type
). If you want to challenge yourself, however, there is more you can do with metaclasses:
- Validation is one of the most prominent examples of where metaclasses can be useful. You can validate to check if attributes/methods are available, you can check if required classes are inherited, and so on. The possibilities are endless.
- Build a metaclass that wraps every method with a decorator (could be useful for logging/debugging purposes), something with a signature like this:
class SomeClass(metaclass=WrappingMeta, wrapper=some_wrapper):
Example answers for these exercises can be found on GitHub: https://github.com/mastering-python/exercises. You are encouraged to submit your own solutions and learn about...