gpt4 book ai didi

python - 如何使用修改后的参数将外部函数包含到python中的类中?

转载 作者:行者123 更新时间:2023-12-04 07:18:37 27 4
gpt4 key购买 nike

我试图在类中包含外部定义的函数。
我制作了很多 Pandas 操作函数并且它们运行良好,但是当我尝试将它们添加到 Class 中时,我遇到了问题。这是我的提纲:
移动电源

import numpy as np
import pandas as pd

df = pd.DataFrame({'A': [1,2,3],'B':[10,20,30],
'C':[100,200,300],'D':[1000,2000,3000]})

@pd.api.extensions.register_dataframe_accessor("my")
class MyAccessor:
def __init__(self, pandas_obj):
self._obj = pandas_obj

def add_1_2(self,col1,col2):
df = self._obj
return df[col1] + df[col2]

df.my.add_1_2('A','B')
这有效(但我已经定义了没有 self._obj 的函数)
# this works
def add_1_3(self,col1,col2,col3):
df = self._obj
return df[col1] + df[col3]

MyAccessor.add_1_3 = add_1_3

df.my.add_1_3('A','B','C')
我的尝试
def temp_fn(df,col1,col2,mydict):
print(mydict)
return df[col1]+df[col2]

col1,col2,mydict = 'A','B',{'lang':'python'}

temp_fn(df,col1,col2,mydict) # calling directly using function works good

# now I want to include this function inside the Class
def make_class_fn(fn, *args, **kwargs):
return fn(args[0]._obj, *args[1:], **kwargs)

MyAccessor.temp_fn = make_class_fn(temp_fn,df,col1,col2,mydict)

AttributeError: 'DataFrame' object has no attribute '_obj'
笔记
如果我只有一个函数,我可以在 Class 中复制相同的函数并在那里编辑它,但是我有大量的函数,这不是一个好主意。
资源
  • Define a method outside of class definition?
  • Python function assignment outside class definition causes argument exception
  • 最佳答案

    您的转换函数只需要创建一个新函数,该函数使用 self._obj 调用原始函数。作为第一个论点。

    from functools import wraps


    def temp_fn(df,col1,col2,mydict):
    print(mydict)
    return df[col1]+df[col2]


    def make_method(f):
    @wraps(f)
    def _(self, col1, col2, mydict):
    return f(self._obj, col1, col2, mydict)
    return _

    MyAccessor.temp_fn = make_method(temp_fn)
    更一般地说, make_method可以处理任意参数,只要第一个参数有 _obj要传递的属性。
    def make_method(f):
    @wraps(f)
    def _(self, *args, **kwargs):
    return f(self._obj, *args, **kwargs)
    return _
    您也可以让 make_method为你执行任务。
    def make_method(cls, f):
    @wraps(f)
    def _(self, *args, **kwargs):
    return f(self._obj, *args, **kwargs)
    setattr(cls, f.__name__, _)

    make_method(MyAccessor, temp_fn)
    或者甚至使它成为装饰器(尽管如果您有要装饰的定义,您可能也可以很容易地直接定义该方法)。
    def make_method(cls):
    def decorator(f):
    @wraps(f)
    def _(self, *args, **kwargs):
    return f(self._obj, *args, **kwargs)
    setattr(cls, f.__name__, _)
    return _
    return decorator


    @make_method(MyAccessor)
    def temp_fn(df, col1, col2, mydict):
    return df[col1] + df[col2]

    关于python - 如何使用修改后的参数将外部函数包含到python中的类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68636604/

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