Python中函数调用问题
当我在leecode上写完代码,自己在pycharm运行的时候,发现老是出错。`
class Solution():
def twoSum(self,nums,target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
self.nums=nums
self.target=target
for i,num in enumerate(nums):
if target - num in d:
return [d[target-num],i]
d[num] = i
B=[2,7,11,15]
A=Solution(B,9)
会报如下的错误:
发现自己好蠢啊,Solution就没有传入形参,怎么能运行成功的呢!
最后,我改了代码,有两种:
class Solution():
def twoSum(self,nums,target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {} # 哈希表
self.nums=nums
self.target=target
for i,num in enumerate(nums):
if target - num in d:
return [d[target-num],i]
d[num] = i
B=[2,7,11,15]
A=Solution()
print(A.twoSum(B,9))
因为代码中写的在twoSum函数中传入参数啊,所以肯定是在twoSum中传入实参。
还有一种:
class Solution():
def __init__(self,nums,target):
self.nums=nums
self.target=target
def twoSum(self):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
self.nums=self.nums
self.target=self.target
for i,num in enumerate(self.nums):
if self.target - num in d:
return [d[self.target-num],i]
d[num] = i
B=[2,7,19,18]
A=Solution(B,20)
print(A.twoSum())
使用__init__(self,…)方法。