2.自定义元类控制类的创建行为

工作中,现有的类可能不能满足实际的个性化需求,那么我们需要自己定义元类来控制类的行为

本篇是对自定义元类控制类的创建行为的理解

自定义元类控制类型为分创建行为和实例化行为,其中控制创建行为是通过__Init__方法实现的。

1)我们知道,根据开发规范,类的名称是要大写的,但开发者不大写当然也可以运行的

2)开发者在创建类时,最好在类中加入一些注释,方便以后回头理解,也方便产品经理的理解,当然开发者不写这些注释也没关系

现在我要告诉你,类名必须大写!新建类必须要有注释!就是这么任性,哈哈

实现代码如下:

class MyPeople(type):
    def __init__(self, class_name, class_bases, class_dic):
        if not class_name.istitle():
            raise TypeError("类的首字母必须大写")
        if not "__doc__" in class_dic or not class_dic["__doc__"].strip():
            raise TypeError("必须有注释,且注释不能为空")
        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()

 

posted on 2018-04-26 22:44  Tarantino  阅读(127)  评论(0编辑  收藏  举报

导航