Search code examples
pythonself

Python classes/functions & self paramter


I have some simple code to find the indexes of 2 elements that add up to a sum. (assume sum exists in list)

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))

I'm trying to learn how to instantiate an object best in Python. In my main function, I thought I'd simplify it by doing it in 1 line instead of 2. You can see my 2 attempts to call the function in this class. The 2nd fails, unless I remove the self parameter from the function parameters. It's because I'm trying to pass 2 instead of 3 arguments.

Anyways, I'm confused why my two implementations are different and why one works and the other doesn't. I'm also not sure I even need self here at all. It seems like self is mostly used when you have __init__ and are defining variables for the class? Since I'm not doing that here, do I even need it at all?


Solution

  • The self parameter is only required (and will only work) for instance methods. Instance methods are also the default type. To use it without an instance, and without the self parameter, decorate it as a 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))