我的代码有什么问题:如何使用类和实例

问题描述 投票:0回答:2
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
Re = Solution(o,m)

它返回了错误:

Solution() takes no arguments
python class instance
2个回答
2
投票

这没有理由成为一个类;一个独立的函数就可以了:

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
Re = twoSum(o,m)

如果你坚持使用类,你需要先创建实例,然后调用它的方法:

Re = Solution().twoSum(o,m)

0
投票

Solution
是一个类,而不是一个方法。您需要拨打
Solution(o, m)
,而不是尝试拨打
Solution.twoSum(o, m)

仅仅因为一个类只包含一个函数并不意味着 python 解释器会将该类解释为该函数的别名。

此外,正如@Thomas所说,最好将该函数移到类之外,因为它不访问实例数据。

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