Python classes/functions & 自身参数

Python classes/functions & self paramter

我有一些简单的代码来查找加起来为和的 2 个元素的索引。 (假设总和存在于列表中)

class Solution(object):
    def twoSum(self, nums, target):
        compliment = []
        for ind, item in enumerate(nums):
            print(ind)
            if item in compliment:
                return [nums.index(target - item), ind]
            compliment.append(target - item)
        return [0, 0]

if __name__ == "__main__":

    result = Solution()
    final = result.twoSum([3, 3], 6)

    #Why does this not work without removing the self parameter??
    #final = Solution.twoSum([3, 3], 6)

    print(str(final))

我正在尝试学习如何在 Python 中最好地实例化一个对象。在我的 main 函数中,我想通过 1 行而不是 2 行来简化它。你可以在这个 class 中看到我调用函数的 2 次尝试。第二次失败,除非我从函数参数中删除 self 参数。这是因为我试图传递 2 个而不是 3 个参数。

无论如何,我很困惑为什么我的两个实现不同以及为什么一个有效而另一个无效。我也不确定我什至需要 self 在这里。当你有 __init__ 并且正在为 class 定义变量时,似乎 self 主要被使用?既然我不在这里这样做,我什至需要它吗?

self 参数仅对实例方法是必需的(并且仅有效)。实例方法也是默认类型。要在没有实例且没有 self 参数的情况下使用它,请将其装饰为 staticmethod:

class Solution(object):
    @staticmethod
    def twoSum(nums, target):
        compliment = []
        for ind, item in enumerate(nums):
            print(ind)
            if item in compliment:
                return [nums.index(target - item), ind]
            compliment.append(target - item)
        return [0, 0]

if __name__ == "__main__":

    final = Solution.twoSum([3, 3], 6)
    print(str(final))

在 Python 中,您可以选择使用静态方法或类方法来装饰您的函数。对于类方法,您需要在方法签名中包含 cls。这是区分两者的一个很好的讨论:

What is the difference between @staticmethod and @classmethod?

顺便说一句 — 对于您的代码,我 高度 建议使用集合而不是数组。它将使您的代码更加高效。检查目标值是否已经出现在集合中平均来说是一个恒定时间的操作。