Reputation: 1524
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?
Upvotes: 1
Views: 89
Reputation: 1350
You can opt to either decorating your function with as a staticmethod or a classmethod in Python. In the case of the classmethod, you would need to have cls
in the method signature. Here is a good discussion to distinguish the two:
What is the difference between @staticmethod and @classmethod?
BTW — for your code, I would highly suggest using a set instead of an array. It will make your code much more efficient. Checking if the target value was already seen in a set is a constant time operation on average.
Upvotes: 0
Reputation: 4674
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))
Upvotes: 1