我正在学习 Python。我不确定如何将列表传递给类中的函数。这是我的例子:
class Solution:
def fn_one(self, strs = []):
print(strs[0])
return strs[0]
strs = ["ab", "abc", "abcs", "abx"]
x = Solution.fn_one(strs)
输出:
IndexError: list index out of range
就像我传递一个空列表一样。我做错了什么?
最佳答案
因为 fn_one
是一个实例方法,所以你将 strs
作为 self
传递,你可以创建一个 Solution 的实例
作为自身传递,strs
作为 strs
列表传递:
x = Solution().fn_one(strs)
输出:
ab
除非这不是您想要的,否则您可以使用 @staticmethod
装饰器将 fn_one
定义为静态方法:
class Solution:
@staticmethod
def fn_one(strs = []): # here, nothing is passed automatically
print(strs[0])
return strs[0]
X = Solution.fn_one(strs)
# Solution().fn_one(strs) would work also, since nothing is passed automatically
或者,作为类方法,使用 @classmethod
装饰器:
class Solution:
@classmethod
def fn_one(cls, strs = []): # here, the class is passed automatically as `cls`
print(strs[0])
return strs[0]
X = Solution.fn_one(strs)
但是如果类和对象都不是方法正常工作所必需的,那么使用静态方法是最好的方法。如果您的类中没有任何处理对象的方法,则不需要类,只需使用函数即可。
关于python - 将列表传递给类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57827833/