Python 面向对象 补充类相关

元类

创建类对象的类 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()

类的创建流程

  1. 检测类对象中是否明确__metaclass__属性
  2. 检测父类中是否存在__metaclass__属性
  3. 检测模块中是否存在__metaclass__属性
  4. 通过内置的type这个元类,来创建这个类对象

元类的应用场景

  1. 拦截类的创建
  2. 修改类
  3. 返回修改之后的类

类的描述

方便理清逻辑关系
方便多人合作开发时的沟通
方便生成项目文档

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值