zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    206. 反转链表
    917. 仅仅反转字母
    哈希表的设计
    387. 字符串中的第一个唯一字符
    Mysql重连错误
    MySQL数据库的优化
    XML基础知识
    JS中的DOM与BOM
    JS中的函数,Array对象,for-in语句,with语句,自定义对象,Prototype
    表格标签,图片标签,框架标签,表单标签
  • 原文地址:https://www.cnblogs.com/tarantino/p/8955452.html
Copyright © 2011-2022 走看看