As part of metaprogramming, a metaclass is one of the most important concepts in Python. A Class in Python defines the functionality of its objects using attributes and methods. In contrast, a meta class defines the functionality of the classes, whereas the metaclass treats the other classes as their data. In OOPs, instances of meta classes are classes. In previous versions of Python, on executing the command "type(class_object)", "<type 'instance'>" was the output. In the latest versions of Python, the output is "<class '__main__.Class_Name'>". In the latest versions, the concepts of class and type are unified, and the output for "type(class_object)" and "class_object.__class__" are the same.
From the above program, one can notice that the results for "__class__" and "type()" are the same. For creating a metaclass for a class, the users are expected to implement the following things.
- A separate class, which is called a metaclass, should be defined before defining the normal classes.
- The metaclass could have an argument called 'type'. This is an optional procedure to follow. The 'type' denotes it as meta class.
- When deriving a class from metaclass, the "metaclass" argument should be defined in the derived class.
In the above program, a class name "Meta" (could be other names also) with the argument of "type" is defined using the code "class Meta (type)". The metaclass consists of a constructor that holds an attribute of attr with the value of 100. Then, class X and class Y are derived from the metaclass "Meta" with the "metaclass = Meta" argument. While executing "X.attr", it displays the value of 100. The following things can be observed from the above program.
- The "Meta" class acts as a Template for the Classes X and Y.
- Being the template, the attributes are also reflected in classes X and Y, which is why the attributes are called without declaring any object for the class.
标签:Python,metaclass,class,Meta,classes,type,Class From: https://www.cnblogs.com/zhangzhihui/p/18254021