元类
创建类对象的类 type
num = 10
print(num.__class__)
s = 'abc'
print(s.__class__)
class Person:
pass
p = Person()
print(p.__class__)
print(int.__class__)
print(str.__class__)
print(Person.__class__)
<class ‘int’>
<class ‘str’>
<class ‘main.Person’>
<class ‘type’>
<class ‘type’>
<class ‘type’>
类的创建方式
通过type函数创建类:
def run(self):
print(self)
xxx = type('Dog', (), {'count': 0, 'run': run})
print(xxx)
print(xxx.__dict__)
d.xxx()
print(d)
d.run()
类的创建流程
- 检测类对象中是否明确__metaclass__属性
- 检测父类中是否存在__metaclass__属性
- 检测模块中是否存在__metaclass__属性
- 通过内置的type这个元类,来创建这个类对象
元类的应用场景
- 拦截类的创建
- 修改类
- 返回修改之后的类
类的描述
方便理清逻辑关系
方便多人合作开发时的沟通
方便生成项目文档
class Person:
"""
关于这个类的描述
Attributes:
count: int 表示人的个数
"""
count = 1
def run(self, distance, step):
"""
这个方法的作用效果
:param distance: 参数的含义,参数的类型int,是否有默认值
:param step:
:return: 返回的结果的含义,返回数据的类型int
"""
print('人在跑')
return distance / step
help(Person)
Help on class Person in module main:
class Person(builtins.object)
| 关于这个类的描述
| Attributes:
| count: int 表示人的个数
|
| Methods defined here:
|
| run(self, distance, step)
| 这个方法的作用效果
| :param distance: 参数的含义,参数的类型int,是否有默认值
| :param step:
|
| weakref
| list of weak references to the object (if defined)
Data and other attributes defined here: |
count = 1 |
生成项目文档
使用内置模块:pydoc
查看文档描述:
python -m pydoc 模块名称
启动本地服务,浏览文档:
python -m pydoc -p 6666
生成指定模块html文档:
python -m pydoc -w 模块名称
使用三方模块:
Sphinx
epydoc
doxygen