Python -- simple application of metaclasses to create specific classes

Meta class

Metaclasses are the "things" used to create classes in Python, and classes in Python are also objects.
Metaclasses are used to create these classes (objects). Metaclasses are classes of classes. You can understand them as follows:

MyClass = MetaClass() ා use metaclass to create an object, which is called "class"
My? Object = myclass()? Use "class" to create an instance object

Application of metaclass

Metaclasses are available when creating a specific type of class (for example, the default instance property is uppercase)

#-*- coding:utf-8 -*-
def upper_attr(class_name, class_parents, class_attr):

    #Traverse the property dictionary to capitalize property names that do not begin with \
    new_attr = {}
    for name,value in class_attr.items():
        if not name.startswith("__"):
            new_attr[name.upper()] = value

    #Call type to create a class
    return type(class_name, class_parents, new_attr)

class Foo(object, metaclass=upper_attr):
    bar = 'bip'

print(hasattr(Foo, 'bar'))
print(hasattr(Foo, 'BAR'))

f = Foo()
print(f.BAR)
#coding=utf-8

class UpperAttrMetaClass(type):
    # __new is a special method called before init
    # __new? Is the method used to create an object and return it
    # And init is only used to initialize the passed in parameters to the object
    # You rarely use new unless you want to be able to control the creation of objects
    # Here, the created object is a class, and we want to be able to customize it, so we rewrite \__
    # You can also do something in init if you want
    # There are also some advanced uses that involve overriding the special method, but we don't use it here
    def __new__(cls, class_name, class_parents, class_attr):
        # Traverse the property dictionary to capitalize property names that do not begin with \
        new_attr = {}
        for name, value in class_attr.items():
            if not name.startswith("__"):
                new_attr[name.upper()] = value

        # Method 1: create class object by 'type'
        return type(class_name, class_parents, new_attr)

        # Method 2: reuse the type. New method
        # That's basic OOP programming. No magic
        # return type.__new__(cls, class_name, class_parents, new_attr)

# Usage of Python 3
class Foo(object, metaclass=UpperAttrMetaClass):
    bar = 'bip'

# The usage of python2
# class Foo(object):#     __metaclass__ = UpperAttrMetaClass
#     bar = 'bip'


print(hasattr(Foo, 'bar'))
# Output: False
print(hasattr(Foo, 'BAR'))
# Output: True

f = Foo()
print(f.BAR)
# Output:'bip'

Note:

  • Metaclass metaclass
  • metaclass specifies type creation

Tags: Programming Python

Posted on Tue, 05 Nov 2019 08:33:22 -0800 by wakenbake