gpt4 book ai didi

python - 基于函数列表以编程方式猴子修补Python中的多个函数

转载 作者:太空宇宙 更新时间:2023-11-03 14:21:02 25 4
gpt4 key购买 nike

我尝试猴子修补几个在函数列表上循环的函数,如下所示:

from pandas import *


class DataFrame(DataFrame):
def new_function(self):
print("I exist")


patch_function = [read_csv, read_json, read_html, read_clipboard, read_excel,
read_hdf, read_feather, read_parquet, read_msgpack,
read_stata, read_sas, read_pickle, read_sql, read_gbq]

for func in patch_function:
orig_func = func

def patch(*args, **kwargs):
return DataFrame(orig_func(*args, **kwargs))

func = patch

df = read_csv('example.csv')
df.new_function()

但是,这似乎不起作用。有人能告诉我为什么它不起作用以及如何做到这一点吗?谢谢!

最佳答案

我发现使用函数名称的字符串列表更容易,而不是污染所有的 pandas 函数。我认为您的问题实际上是更新 pd 模块上的基本函数 - 希望这是有意义的并且能够满足您的需要/期望。

#patched_pandas.py

import pandas as pd

class DataFrame2(pd.DataFrame):
def new_function(self):
print("I exist")


patch_function = ['read_csv', 'read_json', 'read_html', 'read_clipboard', 'read_excel',
'read_hdf', 'read_feather', 'read_msgpack',
'read_stata', 'read_sas', 'read_pickle', 'read_sql']

for func in patch_function:
orig_func = getattr(pd, func)

def patch(func):
def patched(*args, **kwargs):
return DataFrame2(func(*args, **kwargs))
return patched

setattr(pd, func, patch(orig_func))

然后使用时,只需导入并获取修改后的 pandas 版本即可。

#main.py (or wherever)
from patched_pandas import pd

df = pd.read_csv('example.csv')
df.new_function()

关于python - 基于函数列表以编程方式猴子修补Python中的多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47938436/

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