Python читает один из моих классов как переменную и выдает ошибку ссылки - PullRequest
0 голосов
/ 29 марта 2019

У меня есть оператор if / elif, который добавляет объекты в стек. Код отлично работает для первых 3 частей оператора, но выдает ошибки для остальной части. Я пробовал несколько разных вещей, но они просто дают больше ошибок. Заранее спасибо за любую помощь!

class nfa:
    intial, accept = None, None

    def __init__(self, initial, accept):
      self.intial, self.accept = initial, accept

def compile(postfix):
    nfaStack = []

    for c in postfix:
        # join the initial and accept states together to create a loop for your characters
        if c == '*':
            nfa = nfaStack.pop()
            initial, accept = state(), state()

            initial.edge1, nfa.accept.edge1 = nfa.intial
            initial.edge2, nfa.accept.edge2 = accept, accept
            nfaStack.append(nfa(initial, accept))
        # merge the two automata by linking 1's accept to 2's initial states
        elif c == '.': 
            nfa2, nfa1 = nfaStack.pop(), nfaStack.pop()
            nfa1.accept.edge1 = nfa2.intial
            nfaStack.append(nfa1.intial, nfa2.accept)       
        # create new initial and accept states and use them to link nfa1 and nfa2
        elif c == '|':
            nfa2, nfa1 = nfaStack.pop(), nfaStack.pop()
            initial, accept = state(), state()
            initial.edge1, initial.edge2 = nfa1.intial, nfa2.intial
            # both old accept states now point to our new accept state
            nfa1.accept.edge1, nfa2.accept.edge1 = accept, accept
            nfaStack.append(nfa(initial, accept))      
        # creates new states and edges; labels each edge with what the current non-special character is
        else:
            initial, accept = state(), state()
            initial.label = c
            initial.edge1 = accept
            # create instance of class nfa()
            nfaStack.append(nfa(initial, accept))   
    # should only ever have one nfa in the stack
    return nfaStack.pop()

1 Ответ

0 голосов
/ 29 марта 2019

Вы получаете эту ошибку, потому что вы случайно переопределяете nfa в качестве переменной здесь:

# join the initial and accept states together to create a loop for your characters
if c == '*':
    nfa = nfaStack.pop() # `nfa` is now a variable!

Самое простое решение состоит в том, чтобы сделать класс классом NFA, поэтому понятно, чтопеременная и что такое имя класса.Это означало бы изменение строк следующим образом:

# This:
nfaStack.append(nfa(initial, accept))
# Becomes:
nfaStack.append(NFA(initial, accept))
...