============================================= 9: Meeting Metaclasses ============================================= Summary ============ - A class is an object that creates instances - A metaclass is an object that creates classes - The base metaclass is *type* - *type* can also be used as a function to dynamically create classes - A metaclass has to inherit from type - A metaclass goes through the usual stages of calling __new_- to create an instance of the class and __init__ to initialize it - A metaclass also has __prepare__ which can supply a data structure suitable for storing the namespace - Metaclasses can be used for many things but they are mostly sophisticated - Typical uses are implementing a final class and a singleton - The metaclass __call__ is used to convert a class object into a callable - You can override this to control how the class contructs an instance - As a class is a callable it can be used as a decorator with its behavior set by its metaclass's __call__ - As a class is a callable it can also be decorated by either a class or a function - There are many cases where the job of a metaclass can be taken on by a decorator What to use Metaclasses For ============================= - Adding attributes or methods automatically - Enforcing certain rules - Complex projects, frameworks and libraries When to use Metaclasses ========================== - Most day to day programming you *do not* need metaclasses - They are an advanced tool - Django often uses metaclasses Program ============ .. literalinclude:: programs/chapterNine.py :language: python Program Output ================= .. code-block:: console Metaclass of Example: Hello from a dynamically created class! __prepare__ called for class: Worker __new__ called for class: Worker __init__ called for class: Worker __call__ invoked to create instance of Worker Alice is running! This attribute was added automatically Creating new Singleton instance Initializing database connection Returning existing Singleton instance db1 is db2: True