【问题标题】:python, calling a method from another classpython,调用另一个类的方法
【发布时间】:2021-08-28 06:40:47
【问题描述】:

我试图从我的评估类调用sum_method 函数到我的主要类,但是我遇到了很多错误。我想使用new_data 作为我的sum_method 函数的数据参数。

评估类:

class evaluation():

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

    def sum_method(self):
        montant_init = self.data.loc[self.data['Initiateur'] == 'Glovoapp', 'Montant (centimes)'].sum()
        print(montant_init)

主类:

class main(evaluation):

        new_data.to_csv("transactions.csv", index=False)

        self.data = new_data

    def call_sum(self, new_data):
       
        init_eval = evaluation.sum_method(self=new_data)
        print(init_eval)


init_evalobj = main()
init_evalobj.call_sum()

【问题讨论】:

  • 什么错误?给minimal reproducible example
  • 哦,是的,很抱歉没有提供更多细节,它可能是属性错误或 1 个必需的位置参数:
  • edit相应的问题,并将您的代码削减到相关部分。
  • "我想使用 new_data 作为我的 sum_method 函数的数据参数。" ...这不是你在做什么。 sum_method() 不带数据参数,它使用已经在 self.data 成员变量中设置的值。

标签: python class object oop methods


【解决方案1】:

如果您在继承类中使用该方法,只需使用self

所以:

init_eval = self.sum_method()

self 参数在 python 中自动作为第一个参数传递

更新 您还应该返回一个值:

    def sum_method(self):
        montant_init = self.data.loc[self.data['Initiateur'] == 'Glovoapp', 'Montant (centimes)'].sum()
        print(montant_init)
        return montant_init

【讨论】:

  • 谢谢你的回答!我正在尝试(没有错误)但是我看不到输出
  • 能否将问题标记为已回答,谢谢先生
  • 是的,当然,一旦我设法让它工作,我会的。现在,当我运行代码时,它没有给我任何输出。
【解决方案2】:

我建议对这两个类进行一些更改,以将 .data 成员变量封装在基类中。我的偏好还是将计算与显示分开,因此将所有打印语句留在 call_sum() 函数中。

class evaluation:

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

    def sum_method(self):
        montant_init = self.data.loc[self.data['Initiateur'] == 'Glovoapp', 'Montant (centimes)'].sum()
        return montant_init


class main(evaluation):

    def __init__(self):
        # Reduce csv content to what's needed for analysis
        data_csv = pd.read_csv('transactions.csv')

        # --> removing unnecessary data
        new_data = data_csv[['Opération', 'Initiateur', 'Montant (centimes)', 'Monnaie',
                             'Date', 'Résultat', 'Compte marchand', 'Adresse IP Acheteur', 'Marque de carte']]

        # --> saving changes...
        new_data.to_csv("transactions.csv", index=False)

        super().__init__(new_data) //Initialize the base class

    def call_sum(self):
        print('Glovoapp "montant" generated')
        init_eval = self.sum_method() //Call the method from the base class
        print(init_eval)

【讨论】:

    猜你喜欢
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多