2016-02-18 29 views
0

我在Python中存儲一個類的列表,但是當我稍後嘗試訪問它時,它是空的。這裏是相關的代碼和輸出。類存儲Python中的列表

在compiler.py

# globals 
verbose = True 
current_context = "" 

def compile(tokens): 
    global verbose, current_context 

    if verbose: print("verbose output enabled.") 

    # first we want to find all the sections. 
    firstpass_token_id = 0 
    gathered_tokens = [] 
    gather_tokens = False 
    for t in tokens: 
     if gather_tokens: 
      gathered_tokens.append(t) 

     if t == SECTION: 
      current_context = extract_section_name(tokens[firstpass_token_id + 1]) 
      gather_tokens = True 
      if verbose: print("gathering tokens for section", current_context) 

     if t == END: 
      add_section(current_context, gathered_tokens) 
      current_context = "" 

      gathered_tokens.clear() 
      gather_tokens = False 

     firstpass_token_id += 1 

    # then we want to call the main section 
    call_section("main") 

def call_section(name): 
    global verbose, current_context 

    if verbose: print("calling section", name) 

    skip_until_next_end_token = False 

    tokens = get_tokens(name) 
    print(len(tokens)) 

在sections.py

sections = [] 
section_id = 0 

class Section: 
    def __init__(self, id, name, tokens): 
     self.id = id 
     self.name = name 

     print("storing the following tokens in", name) 
     print(tokens) 
     self.tokens = tokens 

    def get_tokens(self): 
     print("retrieving the following tokens from", self.name) 
     print(self.tokens) 
     return self.tokens 

def add_section(name, tokens): 
    global sections, section_id 
    sections.append(Section(section_id, name, tokens)) 
    section_id += 1 


def get_tokens(name): 
    global sections 
    for s in sections: 
     if s.name == name: 
      return s.get_tokens() 

輸出

verbose output enabled. 
gathering tokens for section foo 
storing the following tokens in foo 
['foo()', 'var', 'lmao', '=', '2', 'end'] 
gathering tokens for section main 
storing the following tokens in main 
['main()', 'var', 'i', '=', '0', 'i', '=', '5', 'var', 'name', '=', '"Douglas"', 'var', 'sentence', '=', '"This is a sentence."', 'foo()', 'end'] 
calling section main 
retrieving the following tokens from main 
[] 
0 

注意,這些都是不完整的文件,讓我知道你是否需要看到更多的代碼。我確信這是一件愚蠢的事情,我還沒有和python合作過幾個月。謝謝。

回答

1

您正在通過gathered_tokens,所以您的Section對象有self.tokens = tokens

換句話說,gathered_tokensself.tokens現在指向相同的列表。

然後您撥打gathered_tokens.clear()

現在他們仍然指向相同的列表。這是一個空的列表。

嘗試self.tokens = tokens[:]複製。