gpt4 book ai didi

python - 在所有 python 对象上注入(inject)辅助函数?

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:03 24 4
gpt4 key购买 nike

我正在尝试模仿 Ruby 中的 methods.grep,它只返回调用的任何对象(类或实例)的可用方法列表,通过传递给 grep 的正则表达式模式进行过滤。在交互式提示中调查对象非常方便。

def methods_grep(self, pattern):
""" returns list of object's method by a regexp pattern """
from re import search
return [meth_name for meth_name in dir(self) \
if search(pattern, meth_name)]

由于 Python 的限制,我不太清楚,很遗憾,它不能简单地插入到 object 类祖先中:

object.mgrep = classmethod(methods_grep)
# TypeError: can't set attributes of built-in/extension type 'object'

是否有一些解决方法可以注入(inject)所有类,或者我是否必须坚持使用像 dir 这样的全局函数?

最佳答案

有一个名为 forbiddenfruit 的模块可以让您修补内置对象。它还允许您撤消更改。你可以在这里找到它https://pypi.python.org/pypi/forbiddenfruit/0.1.1

from forbiddenfruit import curse    
curse(object, "methods_grep", classmethod(methods_grep))

当然,在生产代码中使用它可能不是一个好主意。

关于python - 在所有 python 对象上注入(inject)辅助函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24163558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com