| Start |
|---|
| Basic Metaclasses When It is possible to subclass Now, we have a new custom When we create a new class using the In the above example the only baseclass is A special class-level attribute A special Any keyword arguments (except Read this in-depth description of python meta-classes (opens new window) for more details. |
| Singletons using metaclasses A singleton is a pattern that restricts the instantiation of a class to one instance/object. For more info on python singleton design patterns, see here (opens new window). |
Using a metaclass Metaclass syntax Python 2 and 3 compatibility with |
Introduction to Metaclasses What is a metaclass?In Python, everything is an object: integers, strings, lists, even functions and classes themselves are objects. And every object is an instance of a class. To check the class of an object x, one can call Most classes in python are instances of The Simplest MetaclassOK, so there is already one metaclass in Python: That does not add any functionality, but it is a new metaclass, see that MyClass is now an instance of SimplestMetaclass: A Metaclass which does SomethingA metaclass which does something usually overrides |
| Custom functionality with metaclasses Functionality in metaclasses can be changed so that whenever a class is built, a string is printed to standard output, or an exception is thrown. This metaclass will print the name of the class being built. You can use the metaclass like so: The standard output will be: |
| The default metaclass You may have heard that everything in Python is an object. It is true, and all objects have a class: The literal 1 is an instance of Now lets instantiate it: What is the class of Nice, Ok, So what is a metaclass? For now lets pretend it is just a fancy name for the class of a class. Takeaways:
But why should you know about metaclasses? Well, Python itself is quite "hackable", and the concept of metaclass is important if you are doing advanced stuff like meta-programming or if you want to control how your classes are initialized. RemarksWhen designing your architecture, consider that many things which can be accomplished with metaclasses can also be accomplished using more simple semantics:
|
Read Article
https://develop.horje.com/learn/1434/reference