Creational patterns
Creational patterns deal with object instantiation mechanism. Such a pattern might define a way as to how object instances are created or even how classes are constructed.
These are very important patterns in compiled languages such as C or C++, since it is harder to generate types on-demand at run time.
But creating new types at runtime is pretty straightforward in Python. The built-in type
function lets you define a new type object by code:
>>> MyType = type('MyType', (object,), {'a': 1}) >>> ob = MyType() >>> type(ob) <class '__main__.MyType'> >>> ob.a 1 >>> isinstance(ob, object) True
Classes and types are built-in factories. We already dealt with the creation of new class objects and you can interact with class and object generation using metaclasses. These features are the basics for implementing the factory design pattern, but we won't further describe it in this section because...