我有两个方法应该写入同一个列表。
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/