简体   繁体   English

将 function 方法传递到 python 中的 class 中:

[英]Passing a function method into a class in python:

I would like to create a method inside a class that gets a variable and a function as input arguments and return a new value.我想在 class 中创建一个方法,该方法获取一个变量和一个 function 作为输入 arguments 并返回一个新值。 In below example the arbitrary function can be max, min, mean, or...:在下面的示例中,任意 function 可以是最大值、最小值、平均值或...:

import pandas as pd
df = pd.DataFrame( {'col1': [1, 2], 'col2': [4, 6]})
df.max(axis=1), df.min(axis=1), df.mean(axis=1)  # sample of methods that I would like to pass

I would like to do similar through a method inside a class.我想通过 class 中的方法来做类似的事情。 My attempt so far that does not work:到目前为止,我的尝试不起作用:

class our_class():
    def __init__(self, df):
        self.df = df
    
    def arb_func(self, func):
        return self.df.func()

ob1 = our_class(df)
ob1.arb_func(max(axis=1))

Any suggestions appreciated.任何建议表示赞赏。

PS: It is a toy problem here. PS:这是一个玩具问题。 My goal is to be able to get a data frame and do arbitrary number of statistical analysis on it later.我的目标是能够获得一个数据框并在以后对其进行任意数量的统计分析。 I do not want to hardcode the statistical analysis and let it change later if needed.我不想对统计分析进行硬编码,并在需要时让它稍后更改。

You could try this:你可以试试这个:

class our_class():
    def __init__(self, df):
        self.df = df
    
    def arb_func(self, func):
        return func(self.df)

You could then use it like this:然后你可以像这样使用它:

ob1 = our_class(df)
ob1.arb_func(lambda x: x.max(axis=1))

I assume the OP is trying to generate some generic coding interface for educational purposes?我假设 OP 正在尝试为教育目的生成一些通用编码接口?

Here a suggestion (which in my opinion is actually making the usage way more complex than necessary, as many other users have already noted in their questions/comments):这里有一个建议(在我看来,这实际上使使用方式比必要的更复杂,正如许多其他用户已经在他们的问题/评论中指出的那样):

from functools import partial
import pandas as pd

df = pd.DataFrame({"a": [1, 2, 3]})

class our_class():
    def __init__(self, df):
        self.df = df
    
    def arb_func(self, func: str, **kwargs):
        return partial(getattr(pd.DataFrame, func), **kwargs)(df)

ob1 = our_class(df)
print(ob1.arb_func("max", axis=1))
0    1
1    2
2    3
dtype: int64


print(ob1.arb_func("max", axis=0))
a    3
dtype: int64

You can pass the method name as a string (not a function object), create an expression with the help of f-string and evaluate it:您可以将方法名称作为字符串传递(不是 function 对象),在 f-string 的帮助下创建一个表达式并对其进行评估:

class our_class():
    def __init__(self, df):
        self.df = df
    
    def arb_func(self, func):
        return eval(f"self.df.{func}")

ob1 = our_class(df)
ob1.arb_func("max(axis=1)")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM