Example of metaclass usage in python

  • 2020-04-02 14:14:51
  • OfStack

This article illustrates the use of metaclasses in python. Specific methods are analyzed as follows:

A metaclass is aclass that is used to create aclass

2. Type (object): returns the type of an object with the same value as object.s Type (name,bases,dict): create a new type, name is the name of the new class, and store the value in the property of s/s, bases is the tuple type, and the value will be stored in s/ss/ss/s

class X:
...     a = 1
...
X = type('X', (object,), dict(a=1))

3. The class is created with type() by default, and the class creation process can be customized by specifying the metaclass parameter or inheriting from aclass when defining the class, which specifies the metaclass parameter

class OrderedClass(type):
     # The method returns a value of __new__ the namespace Parameter if there is no method namespace The value is dict()
     @classmethod
     def __prepare__(metacls, name, bases, **kwds):
        return collections.OrderedDict()
     #namespace is class the __dict__, this dict The object of type has been populated with the corresponding value
     def __new__(cls, name, bases, namespace, **kwds):
        result = type.__new__(cls, name, bases, dict(namespace))
        result.members = tuple(namespace)
        return result class A(metaclass=OrderedClass):
    def one(self): pass
    def two(self): pass
    def three(self): pass
    def four(self): pass
print(A.members)
#('__module__', '__qualname__', 'one', 'two', 'three', 'four')

I hope this article has helped you with your Python programming.


Related articles: