2013-10-12 3 views
0

저는 Python을 처음 사용합니다. 이 부분을 함수 전체에서 공유되는 변수로 만들고 싶습니다.Python : 함수간에 변수 공유

 publist = [] 
    publication = {"pubid" : 1, "title" : 2, "year" : 3, "pubtype" : 4, "pubkey" :5} 
    article = False 
    book = False 
    inproceeding = False 
    incollection = False 
    pubidCounter = 0 

어디서 변수를 배치합니까? 아래에 나와있는 것처럼 배치하려고 시도했지만 indentation에 오류가 있다고합니다. 그러나 외부에 배치하면 들여 쓰기 오류가 발생합니다. 당신이 클래스 로컬로 정의가처럼 그들을 배치 할 때

import xml.sax 


class ABContentHandler(xml.sax.ContentHandler): 
    publist = [] 
    publication = {"pubid" : 1, "title" : 2, "year" : 3, "pubtype" : 4, "pubkey" :5} 
    article = False 
    book = False 
    inproceeding = False 
    incollection = False 
    pubidCounter = 0 

    def __init__(self): 
     xml.sax.ContentHandler.__init__(self) 

    def startElement(self, name, attrs): 

     if name == "incollection": 
      incollection = true 
      publication["pubkey"] = attrs.getValue("pubkey") 
      pubidCounter += 1 

     if(name == "title" and incollection): 
      publication["pubtype"] = "incollection" 



    def endElement(self, name): 
     if name == "incollection": 

      publication["pubid"] = pubidCounter 
      publist.add(publication) 
      incollection = False 

    #def characters(self, content): 


def main(sourceFileName): 
    source = open(sourceFileName) 
    xml.sax.parse(source, ABContentHandler()) 


if __name__ == "__main__": 
    main("dblp.xml") 

답변

2

, 따라서 당신은 self

예를 통해 검색 할 필요가

def startElement(self, name, attrs): 

    if name == "incollection": 
     self.incollection = true 
     self.publication["pubkey"] = attrs.getValue("pubkey") 
     self.pubidCounter += 1 

    if(name == "title" and incollection): 
     self.publication["pubtype"] = "incollection" 

오히려 그들을 위해 글로벌 될 것입니다 경우 클래스 정의에 변수를 배치 할 때이 방법으로 이러한 변수를 참조 할 수 있습니다

1

, 당신은 클래스 외부를 정의해야합니다 self.incollection (자기 클래스 인스턴스입니다. 이렇게하지 않으면 (단지이 변수들을 과 같은 이름으로 참조) Python은 전역 변수에서 이들 변수를 찾으려고합니다. 따라서 변수를 전역 변수로 정의하고이 변수를 참조하기 전에 global 키워드를 사용하십시오.

global incollection 
incollection = true 
관련 문제