You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数返回注解->无报错,如何强制返回指定类型?

如何强制Python函数返回指定类型?

Python的函数返回注解(比如-> int)仅作为文档提示和静态检查标记,Python解释器默认不会在运行时验证返回值的实际类型,所以你的代码中number_authors返回字符串却不报错是正常行为。

要强制函数返回指定类型,可以用以下两种方法:

方法一:函数内手动校验返回值

在函数返回结果前,直接用isinstance检查类型,不符合则抛出异常:

class Book(Document):
    # ...其他代码保持不变...
    def number_authors(self) -> int:
        result = "3"
        if not isinstance(result, int):
            raise TypeError("number_authors必须返回int类型")
        return result

方法二:用装饰器实现通用类型校验

编写一个通用装饰器,用于统一检查函数返回值类型,可复用在多个函数上:

from functools import wraps

def enforce_return_type(expected_type):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            if not isinstance(result, expected_type):
                raise TypeError(f"函数{func.__name__}要求返回{expected_type.__name__}类型,实际返回{type(result).__name__}类型")
            return result
        return wrapper
    return decorator

# 在Book类的方法上应用装饰器
class Book(Document):
    # ...其他代码保持不变...
    @enforce_return_type(int)
    def number_authors(self) -> int:
        return "3"

调用doc1.number_authors()时,会直接抛出TypeError,强制保证返回值类型符合要求。

另外,如果只是想在开发阶段提前发现类型不匹配问题,可以使用静态类型检查工具(如mypy),运行mypy 你的脚本文件名.py即可检测到返回值与注解不一致的问题,但它不会影响程序运行时的行为。

内容的提问来源于stack exchange,提问作者Alucard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:11:05