简体   繁体   English

全局变量在功能中无法识别

[英]Global variable not recognized in functions

I know that this question looks exactly like so many other on here, because I just read them all and they all say to do what I already tried, and it hasn't worked (or I'm missing a subtle difference with my situation). 我知道这个问题看起来和其他许多人一样,因为我只读了所有这些问题并且他们都说要做我已经尝试过的事情,而且它没有奏效(或者我错过了与我的情况有细微差别) 。 Here is my situation: 这是我的情况:

I am writing a scraper using Scrapy and Python 2.7.11, and my code looks like this (this is a copy and paste with irrelevant lines omitted, but I can re-add them upon request): 我正在使用Scrapy和Python 2.7.11编写一个刮刀,我的代码看起来像这样(这是一个复制和粘贴,省略了不相关的行,但我可以根据要求重新添加它们):

class LbcSubtopicSpider(scrapy.Spider):

    ...omitted...

    rawTranscripts = []
    rawTranslations = []

    def parse(self, response):
        #global rawTranscripts, rawTranslations
        rawTitles = []
        rawVideos = []
        for sel in response.xpath('//ul[1]'): #only scrape the first list

        ...omitted...

            index = 0
            for sub in sel.xpath('li/ul/li/a'): #scrape the sublist items
                index += 1
                if index%2!=0: #odd numbered entries are the transcripts
                    transcriptLink = sub.xpath('@href').extract()
                    #url = response.urljoin(transcriptLink[0])
                    #yield scrapy.Request(url, callback=self.parse_transcript)
                else: #even numbered entries are the translations
                    translationLink = sub.xpath('@href').extract()
                    url = response.urljoin(translationLink[0])
                    yield scrapy.Request(url, callback=self.parse_translation)

        print rawTitles
        print rawVideos
        print rawTranslations

    def parse_translation(self, response):
        global rawTranslations
        for sel in response.xpath('//p[not(@class)]'):
            rawTranslation = sel.xpath('text()').extract()
            rawTranslations.append(rawTranslation)

This will return an error any time either "print rawTranslations" or "rawTranslations.append(rawTranslation)" is called because the global "rawTranslations" is not defined. 每次调用“print rawTranslations”或“rawTranslations.append(rawTranslation)”时都会返回错误,因为未定义全局“rawTranslations”。

As I said before, I have looked into this pretty extensively and pretty much everyone on the internet says to just add a "global (name)" line to the beginning of any function you'd use/modify it in (although I'm not assigning to it ever, so I shouldn't even need this). 正如我之前所说的那样,我已经广泛地研究了这一点,互联网上的每个人都说只需要在你使用/修改它的任何函数的开头添加一个“全局(名称)”行(虽然我是没有分配给它,所以我甚至不需要这个)。 I get the same result whether or not my global lines are commented out. 无论我的全局行是否被注释掉,我都得到相同的结果。 This behavior seems to defy everything I've read about how globals work in Python, so I suspect this might be a Scrapy quirk related to how parse functions are called through scrapy.Request(....). 这种行为似乎无视我读过的关于全局变量如何在Python中运行的所有内容,所以我怀疑这可能是一个与scrapy函数通过scrapy.Request(....)调用有关的Scrapy怪癖。

Apologies for posting what appears to be the same question you've seen so much yet again, but it seems to be a bit twisted this time around and hopefully someone can get to the bottom of it. 抱歉发布看起来像你已经看过很多的同一个问题,但这次似乎有点扭曲,希望有人可以深究它。 Thanks. 谢谢。

In your case the variable you want to access is not global, it is in the scope of the class. 在您的情况下,您要访问的变量不是全局变量,它位于类的范围内。

global_var = "global"

class Example:

    class_var = "class"

    def __init__(self):
         self.instance_var = "instance"

    def check(self):
        print(instance_var) # error
        print(self.instance_var) # works
        print(class_var) # error
        print(self.class_var) # works, lookup goes "up" to the class
        print(global_var) # works
        print(self.global_var) # works not

You only need the global keyword if you want to write to a global variable. 如果要写入全局变量,则只需要global关键字。 Hint: Don't do that because global variables that are written to bring nothing but pain and despair. 提示:不要这样做,因为写入的全局变量只能带来痛苦和绝望。 Only use global variables as (config) constants. 仅将全局变量用作(config)常量。

global_var = "global"

class Example:

    def ex1(self):
        global_var = "local" # creates a new local variable named "global_var"

    def ex2(self):
        global global_var
        global_var = "local" # changes the global variable

Example().ex1()
print(global_var) # will still be "global"
Example().ex2()
print(global_var) # willnow be "local"

if you want to use variable in class, you can use self.xxx 如果要在类中使用变量,可以使用self.xxx

class A:
...     var = []
...     def test(self):
...         self.var.append(10)
...         print self.var

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM