python 函数增加元信息

本文介绍Python中函数注解的使用方法,包括参数类型注解、返回值类型注解及多参数注解等,并演示如何通过函数的__annotations__属性获取这些元信息。此外,还介绍了如何使用functools库中的wraps装饰器来保留被装饰函数的原始元信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
# ========================================================
# Module         :  function_annotations
# Author         :  luting
# Create Date    :  2018/6/4
# Amended by     :  luting
# Amend History  :  2018/6/4
# ========================================================


# 添加函数元信息
def test_01(x: int, y: int) -> int:
    # x:数据类型, -> 返回值数据类型
    return x+y


def test_02(x: int, y: 'default 5'=5) -> int:
    return x+y


# 多参数注释
def test_03(message: dict(type=str, help='the test message')) -> str:
    return message

# 函数的注解存储在函数__annotations__
print(test_03.__annotations__)


# 创建装饰器保留函数元信息
# 使用 functools 库中的 @wraps 装饰器来注解底层包装函数
from functools import wraps


def test_04(func):

    @wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result

    return wrapper


@test_04
def login():
    """
    test
    """
    pass

print(login.__doc__)

 

转载于:https://www.cnblogs.com/xiaoxiaolulu/p/9132781.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值