python - 如何在 python 中定义全局列表

标签 python

我有两个方法应该写入同一个列表。

class MySpider():

    def parse_post(self, response):
        commentList = []
        ...  
        commentList.append(someData)

    def parse_comments(self, response):
        commentList = []
        ...  
        commentList.append(someData)

在此代码中有两个 commentList 列表,但我需要一个列表,我可以在其中附加数据。我想在这个类的任何方法中访问这个列表。我试过

class MySpider():

    commentNum = []

    def parse_post(self, response):
        ...  
        commentList.append(someData)

    def parse_comments(self, response):
        ...  
        commentList.append(someData)

但这给了我一个错误global name commentList is not defined。关于如何拥有一个可以在该类中的所有方法中访问的列表,有什么想法吗?

最佳答案

一种方法是简单地通过全名引用变量(MySpider.commentList):

class MySpider(object):

    commentList = []

    def parse_post(self, response):
        ...  
        MySpider.commentList.append(someData)

    def parse_comments(self, response):
        ...  
        MySpider.commentList.append(someData)

这样 MySpider 的所有实例将共享同一个变量

如果您可能有多个 MySpider 实例,并且希望每个实例都有自己的 commentList,那么只需在构造函数中创建它并将其引用为 self.commentList:

class MySpider(object):

    def __init__(self):    
        self.commentList = []

    def parse_post(self, response):
        ...  
        self.commentList.append(someData)

    def parse_comments(self, response):
        ...  
        self.commentList.append(someData)

如果这两个版本都适用于您的情况,我建议您使用后者。

关于python - 如何在 python 中定义全局列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7385997/

相关文章:

python - 类型错误 : 'Connection' object is not callable in python scripting using mysqldb

python - 在python中查找哪个函数正在使用给定的类

python替换列表中的项目

python - 你如何在 Pandas 中合并 2 个系列

python - 我想用keras为深度学习添加一对一层

python - 使用字典中的数据创建一个简单的 python 条形图/直方图

python - 如何设置/删除跨域cookie?

python - 合并两个无可比拟的排序元素列表,在 python3 中保持它们的相对顺序

python - 使用 unicode 以任何语言保存文件

python - 如何测试两个稀疏数组是否(几乎)相等?