【问题标题】:Specify helper function that's used by another helper function inside a class指定类中另一个辅助函数使用的辅助函数
【发布时间】:2021-06-01 02:29:41
【问题描述】:

更新问题:

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

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

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()

【问题讨论】:

  • 使用self.add_constant

标签: python pandas class


【解决方案1】:

静态@staticmethod如何访问self

Static method can be called without creating an object or instance. 那么在创建任何对象之前调用staticmethod 时,self 会是什么? PS。好吧,这就是我的观点,我可能是错的(我是 python 新手,在 C/C++/Java 中就是这样)。 也许你需要打电话给DataManipulation.helper_func(5) 而不是self.helper_func(5)

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-23
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    相关资源
    最近更新 更多