Python类调用max_profit_assignment方法报错:参数数量不匹配
TypeError报错原因分析
问题重现
你定义了Profile类的max_profit_assignment方法,通过实例调用时触发报错:
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))
执行后抛出错误:
File "C:\Users\jerry\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中,实例方法的第一个参数必须是self(参数名可自定义,但行业约定用self),它代表调用该方法的实例本身。
你定义max_profit_assignment时只声明了3个参数,但通过profile实例调用方法时,Python会自动把实例profile作为第一个参数传递给方法,导致实际传递了4个参数(实例本身 + difficulty + profit + worker),而方法仅接受3个,因此触发参数不匹配的TypeError。
修复方案
有两种可行的修复方式:
- 改为标准实例方法,添加
self作为第一个参数:
class Profile: def max_profit_assignment(self, difficulty, profit, worker): # 原有代码逻辑保持不变 jobs = [JOB(difficulty[i], profit[i]) for i in range(len(difficulty))] # ... 后续代码省略
- 如果该方法不需要依赖实例的任何属性,可定义为静态方法,用
@staticmethod装饰器省略self参数:
class Profile: @staticmethod def max_profit_assignment(difficulty, profit, worker): # 原有代码逻辑保持不变 jobs = [JOB(difficulty[i], profit[i]) for i in range(len(difficulty))] # ... 后续代码省略
内容的提问来源于stack exchange,提问作者JerryBurnard
相关产品推荐
相关产品推荐

