美文网首页
文档字符串和类型提示

文档字符串和类型提示

作者: defphot | 来源:发表于2019-10-14 08:41 被阅读0次

文档字符串和类型提示

原则

  1. 文档字符串说明操作或使用方法而不是解释理由
  2. 文档字符串是文档而不是注释
  3. 在代码中添加注释不是一个好的实践
    • 注释表示未能在代码中准确表达想法。如果必解释原因或实现步骤,那证明代码不够好。
    • 注释可能产生误导。修改代码往往忘记更新注释,过时的注释和现有代码的逻辑常常令人感到困惑。
  4. 极少数情况下,无法避免注释,这种情况下可以接受描述性的注释。
  5. 多写文档字符串,少写注释。

示例

class MyDict(dict):
    def update(self, E=None, **F):
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        
        >>> d = MyDict()
        >>> d.update({1: "one", 2: "two"})
        >>> d
        {1: "one", 2: "two"}
        >>> d.update([(3, "three"), (4, "four")])
        >>> d
        {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
        """
        super().update()

文档字符串会存储在对象的__doc__属性中

def my_function():
    """
    Run some computation
    """
    return None

print(my_function.__doc__)
# 'Run some computation'

Python3中引入了类型提示

class Point:
    def __init__(self, lat, long):
        self.lat = lat
        self.long = long

def locate(latitude: float, longitude: float) -> Point:
    """
    Find an object in the map by its coordinates
    """
    return Point(latitude, longitude)

print(locate.__annotations__)
# {'latitude': <class 'float'>, 'longitude': <class 'float'>, 'return': <class 'Point'>}

class Point:
    lat: float
    long: float

print(Point.__annotations__)
# {'lat': <class 'float'>, 'long': <class 'float'>}

文档字符串和类型提示结合

def data_from_response(response: dict) -> dict:
    """
    If the response is OK, return its payload.
    - response: a dict like:
    {
        "status": 200, # <int>
        "timestamp": "....", # ISO format string of the current date time
        "payload": { ... } # dict with the returned data
    }
    - Returns a dict like:
    {
        "data": { ... } 
    }
    - Raises:
        - ValueError if the HTTP status is != 200
    """
    if response["status"] != 200:
        raise ValueError
    return {"data": response["payload"]}

详细了解类型提示请查看mypy

相关文章

  • 文档字符串和类型提示

    文档字符串和类型提示 原则 文档字符串说明操作或使用方法而不是解释理由 文档字符串是文档而不是注释 在代码中添加注...

  • 3.Python编程之数据类型

    原文文档 类型的概念 Python语言的类型 数字类型,字符串类型,元组类型 列表类型,文件类型,字典类型 3...

  • Kotlin 教程之【基本类型】

    参考文档:点击这里 数字 字符 布尔 数组 字符串 数字 类型 字面常量 数字类型的字面常量支持十进制、二进制和十...

  • 对于PyCharm某些库没有自动提示的处理

    前言 resp没法提示.decode()之类的pycharm帮助文档有提供类型定义,方便我们自动智能提示 解决方案...

  • 翻渣mongoengine文档

    创建model 文档都是继承Document类。预留:字段类型: StringField,字符串。 ListFie...

  • 映射

    一、概述 (1)映射映射是定义文档如何被存储和索引的,包括含有哪些字段,字段的类型,字符串类型的字段应当作为全文本...

  • 学习纲要:文档类型

    学习目标 知道什么是文档类型 知道HTML5 推荐的文档类型该怎么写 了解怪异模式和标准模式 学习资源 文档类型和...

  • 各种类型

    字符串类型 单引号 和 双引号 都可以定义字符串类型。 toString()方法将其他类型转换为字符串类型 再字符...

  • 关于Mongo的基本操作

    MongoDB基本语法——数据类型 .ObjectID:文档id.String:字符串.Boolean:布尔值.I...

  • redis 常用命令

    一、概要 中文文档 Redis 支持 5 中数据类型:string(字符串),hash(哈希),list(列表),...

网友评论

      本文标题:文档字符串和类型提示

      本文链接:https://www.haomeiwen.com/subject/nhylmctx.html