Python在类中存储列表

时间:2016-02-18 23:26:10

标签: 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 个答案:

答案 0 :(得分:1)

您正在传递gathered_tokens,因此您的Section对象有self.tokens = tokens

换句话说,gathered_tokensself.tokens现在指向同一个列表。

然后你拨打gathered_tokens.clear()

现在他们仍然指向同一个名单。这是一个空列表。

尝试self.tokens = tokens[:]制作副本。