python - 将列表传递给类中的函数

标签 python list function

我正在学习 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/

相关文章:

python - gevent猴子补丁命令

python - python中对列表列表的第i项求和的快速方法

c++ - 函数的返回值类型是别名***或 bool 值

arrays - 在设备上运行时调用错误中的额外参数

javascript - 从 RESTful 服务查看主干数据

CSV文件的python Dictread,数据中包含NUL字节

java - Java中从父列表调用子方法

Python,多处理库问题

python - 理解数据类型python

c++ - 关于STL列表中插入元素的一个问题