ZhangZhihui's Blog  

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.

  1. A separate class, which is called a metaclass, should be defined before defining the normal classes.
  2. The metaclass could have an argument called 'type'. This is an optional procedure to follow. The 'type' denotes it as meta class.
  3. 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.

  1. The "Meta" class acts as a Template for the Classes X and Y.
  2. 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.

 

posted on 2024-06-18 11:35  ZhangZhihuiAAA  阅读(6)  评论(0编辑  收藏  举报