指定由类中的另一个辅助函数使用的辅助函数

时间:2021-06-01 02:29:41

标签: python pandas class

问题更新:

我想在我的类中包含一个辅助函数,该函数使用另一个仅在该类的一个方法中使用的辅助函数。如果我有一个静态方法,我会使用 @staticmethod 和 self.func_name 。但是,如果我想从静态方法中调用另一个静态方法并指定使用 self.helper_func,我会得到一个 'name 'self “未定义”错误。

为了给您一些背景信息,我这样做的原因是因为在我的实际用例中,我正在处理一组分组数据框。然后在外部 apply 语句中,我遍历每个分组数据框中的特定列集并应用实际函数。因此,外部助手函数只是对分组数据帧中的组进行应用,然后调用内部助手对列组进行操作。

import pandas as pd
import numpy as np

class DataManipulation():

    def __init__(self, data):
        self.data = data

    @staticmethod
    def helper_func(const):
        return const
    
    @staticmethod
    def add_constant(var):
        res = var+self.helper_func(5)
        return res


    def manipulate_data(self):
        res = self.data.apply(add_constant)
        return res

test_df = pd.DataFrame({'a': np.arange(4), 'b': np.arange(4)})
data_manip = DataManipulation(test_df)
data_manip.manipulate_data()

1 个答案:

答案 0 :(得分:1)

静态@staticmethod如何访问self

Static method can be called without creating an object or instance. 那么在创建任何对象之前调用 selfstaticmethod 会是什么? 附注。好吧,这就是我的观点,我可能错了(我是 Python 新手,这就是 C/C++/Java 中的情况)。 也许您需要调用 DataManipulation.helper_func(5) 而不是 self.helper_func(5)