保证用户设计的类必须有文档注释,不能为空 ,同时要求在一个类内部定义的所有函数必须有文档注释,不能为空。

    1. class MyMetaClass(type):
    2. def __new__(cls, cls_name, cls_bases, cls_dict):
    3. print(cls) #注意:<class '__main__.MyMetaClass'>
    4. if '__doc__' not in cls_dict or len(cls_dict['__doc__'].strip()) == 0:
    5. raise TypeError('类:%s 必须有文档注释,并且注释不能为空.' % cls_name)
    6. for key, value in cls_dict.items():
    7. if key.startswith('__'):
    8. continue
    9. if not callable(value):
    10. continue
    11. if not value.__doc__ or len(value.__doc__.strip()) == 0:
    12. raise TypeError('函数:%s 必须有文档注释,并且文档注释不能为空.' % (key))
    13. obj = super().__new__(cls,cls_name,cls_bases,cls_dict)
    14. print(obj) #<class '__main__.Person'> 创建出来的就是Person类,是我们需要的.
    15. return obj
    1. class Person(object,metaclass=MyMetaClass): #这一行: Person = MyMetaClass('Person',(object,),{...})
    2. """
    3. 元类.
    4. """
    5. country = 'China'
    6. def __init__(self,name,age):
    7. self.name = name
    8. self.age = age
    9. def tell_info(self):
    10. """
    11. 绑定方法.
    12. """
    13. print('%s 的年龄是:%s'%(self.name,self.age))