Python类与实例使用问题:创建Solution实例时报错‘Solution() takes no arguments’
问题排查与修正
报错原因很直接:你创建Solution实例时写了Solution(o,m),给类的构造传了参数,但你的Solution类没有定义接收参数的构造方法(__init__)。Python默认的构造方法不带额外参数(仅self),所以会触发Solution() takes no arguments的错误。
你的代码逻辑是把两数之和的实现写在了twoSum方法里,但调用方式错了——应该先创建Solution的空实例,再调用这个实例的twoSum方法并传参,而非把参数直接传给类的构造。
修正后的常规写法
from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: n = len(nums) for i in range(n - 1): for j in range(i + 1, n): if nums[i] + nums[j] == target: return [i, j] return [] # No solution found o = [2, 6, 7, 5, 3] m = 9 # 先创建空实例,再调用twoSum方法传参 sol_instance = Solution() result = sol_instance.twoSum(o, m) print(result) # 输出[0, 2],循环先找到2+7=9的组合
另一种写法(静态方法,无需创建实例)
如果不需要维护实例属性,也可以把twoSum改成静态方法,直接通过类调用:
from typing import List class Solution: @staticmethod def twoSum(nums: List[int], target: int) -> List[int]: n = len(nums) for i in range(n - 1): for j in range(i + 1, n): if nums[i] + nums[j] == target: return [i, j] return [] # No solution found o = [2, 6, 7, 5, 3] m = 9 # 直接用类调用静态方法 result = Solution.twoSum(o, m) print(result)
内容的提问来源于stack exchange,提问作者ParBloParMoo
相关产品推荐
相关产品推荐

