Singletons and metaclasses
Let's start with a brief introduction to metaclasses. A metaclass is a class of a class, which means that the class is an instance of its metaclass. With metaclasses, programmers get an opportunity to create classes of their own type from the predefined Python classes. For instance, if you have an object, MyClass
, you can create a metaclass, MyKls
, that redefines the behavior of MyClass
to the way that you need. Let's understand them in detail.
In Python, everything is an object. If we say a=5
, then type(a)
returns <type 'int'>
, which means a
is of the int type. However, type(int)
returns <type 'type'>
, which suggests the presence of a metaclass as int is a class of the type
type.
The definition of class is decided by its metaclass, so when we create a class with class A
, Python creates it by A = type(name, bases, dict)
:
name
: This is the name of the classbase
: This is the base classdict
: This is the attribute variable
Now...