Custom metaclass controls class creation behavior

At work, the existing classes may not meet the actual personalized needs, so we need to define our own metaclass to control the behavior of the class

This article is an understanding of the creation behavior of custom metaclass control classes

The custom metaclass control type is divided into creation behavior and instantiation behavior, and the control creation behavior is realized through the __Init__ method.

1) We know that according to the development specification, the name of the class should be capitalized, but of course developers can run without capitalization

2) When developers create a class, it is best to add some annotations to the class, which is convenient for later understanding and easy for product managers to understand. Of course, it does not matter if the developer does not write these annotations

Now I'm going to tell you that class names must be capitalized! New classes must have annotations! It's so capricious, haha

The implementation code is as follows:

class MyPeople(type):
     def  __init__ (self, class_name, class_bases, class_dic):
         if  not class_name.istitle():
             raise TypeError( " The first letter of a class must be capitalized " )
         if  not  " __doc__ "  in class_dic or  not class_dic[ " __doc__ " ].strip():
             raise TypeError( " There must be a comment, and the comment cannot be empty " )
        super(MyPeople, self).__init__(class_name, class_bases, class_dic)


class People(object, metaclass=MyPeople):
    """
    there must be doc,
    and the doc must be in the first line
    """
    country = "China"
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def tell_info(self):
        print(f"{self.name} is from {self.country}, and he is {self.age} years old")


chen = People("chenjun", 21)
chen.tell_info()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324921695&siteId=291194637