无法调用Python类中的方法

问题描述 投票:0回答:1

我正在尝试执行以下代码,但最后一行代码给出错误。 我在

max_profit_assignment
类中有方法
Profile
,当我尝试使用配置文件对象执行它时,它给出了错误。

class JOB:
    def __init__(self, job, profit):
        self.job = job
        self.profit = profit

class Profile:
    def max_profit_assignment(difficulty, profit, worker):
        jobs = [JOB(difficulty[i], profit[i]) for i in range(len(difficulty))]

        n = len(worker)
        i = 0
        current_profit = 0
        max_profit = 0

        for able in worker:
            while i < n:
                if jobs[i].job <= able:
                    current_profit = max(current_profit, jobs[i].profit)
                i += 1
            i = 0

            print(current_profit)
            max_profit += current_profit
            current_profit = 0

        return max_profit

if __name__ == "__main__":
    difficulty = [5, 50, 92, 21, 24, 70, 17, 63, 30, 53]
    profit = [68, 100, 3, 99, 56, 43, 26, 93, 55, 25]
    worker = [96, 3, 55, 30, 11, 58, 68, 36, 26, 1]
    profile = Profile()
    print(dir(profile))
    print(profile.max_profit_assignment(difficulty, profit, worker))

print(profile.max_profit_assignment(难度,利润,工人)) 这行报错,为什么?

  File "C:\Users\pran.sukh\Downloads\GOLong\PythonCode\Profile.py", line 34, in <module>
    print(profile.max_profit_assignment(difficulty, profit, worker))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Profile.max_profit_assignment() takes 3 positional arguments but 4 were given
python-3.x
1个回答
0
投票

这是因为您尝试调用的方法

max_profit_assignment
是静态方法,并且您尝试访问它的方式就像调用实例方法一样。为此,您需要更改方法签名,将
self
关键字添加到
max_profit_assignment
方法中即可正常工作。

   class Profile:
       def max_profit_assignment(self, difficulty, profit, worker):

添加

self
作为方法签名中的第一个参数。

© www.soinside.com 2019 - 2024. All rights reserved.