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

如何查看Python中可作用于指定对象的内置函数?

如何获取可作用于Python对象的所有内置函数

首先明确:dir(obj)返回的是对象自身的属性和方法,而像max()、len()这类内置函数是独立于对象本身的——它们通过接收对象作为参数来工作,所以不会出现在对象的方法列表里。

要找出所有能作用于某个对象的内置函数,可以用以下几种方法:

方法一:遍历内置函数并测试兼容性

遍历所有内置函数,尝试将目标对象作为参数传入,能正常执行的就是可作用于该对象的函数。

示例代码(以列表对象为例):

import builtins

# 提取所有可调用的内置函数
all_builtin_funcs = [name for name in dir(builtins) if callable(getattr(builtins, name))]

test_list = [1, 2, 3]
applicable_funcs = []

for func_name in all_builtin_funcs:
    func = getattr(builtins, func_name)
    try:
        # 尝试用目标对象调用函数,捕获不兼容的异常
        func(test_list)
        applicable_funcs.append(func_name)
    except (TypeError, ValueError):
        continue

print(applicable_funcs)

运行后会得到len、max、min、sum、any、all等可直接处理列表的内置函数。

注意:这种方法有局限性——比如map()需要配合函数和列表一起使用,单独传列表会报错,但它确实能处理列表,这类情况需要额外调整判断逻辑。

方法二:用inspect模块检查函数签名

通过inspect模块解析函数的参数签名,判断目标对象的类型是否匹配函数的参数要求。

示例代码:

import builtins
import inspect

test_list = [1, 2, 3]
list_type = type(test_list)
applicable_funcs = []

for func_name in dir(builtins):
    func = getattr(builtins, func_name)
    if not callable(func):
        continue
    try:
        sig = inspect.signature(func)
        # 检查是否有参数能接收列表类型
        for param in sig.parameters.values():
            if param.annotation is inspect.Parameter.empty or issubclass(list_type, param.annotation):
                applicable_funcs.append(func_name)
                break
    except (ValueError, TypeError):
        continue

# 去重并排序
applicable_funcs = sorted(list(set(applicable_funcs)))
print(applicable_funcs)

这种方法更严谨,但依赖函数的类型标注,部分内置函数可能没有完善的标注,结果会有少量偏差。

方法三:查阅官方文档

如果需要最准确的清单,直接查看Python官方文档中内置函数的参数说明,每个函数都会明确标注支持的参数类型,手动筛选出可处理目标对象的函数即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:06:25