I wonder why class variables are continuously initialized in Python.

Asked 2 years ago, Updated 2 years ago, 97 views

class Stack:

    def __init__(self):
        self.items = []

    def __len__(self):
        return len(self.items)

    def is_empty(self):
        return len(self.items) == 0

    def push(self,e):
        self.items.append(e)

    def pop(self):
        if self.is_empty():
            raise Exception('Stack is empty')
        else:
            return self.items.pop()

    def top(self):
        if self.is_empty():
            raise Exception('Stack is empty')
        else:
            return self.items[-1]


valStack = Stack()
opStack = Stack()

def repeatOps(refOp):
    while ( len(valStack) > 1 or prec(refOp) <= prec(opStack.top()) ) :
        doOP()

def EvalExp( exp ):
    for e in exp:
        if e in '0123456789':
            valStack.push(e)
        else:
            if opStack.is_empty():
                opStack.push(e)
            else:
                repeatOps(e)
                opStack.push(e)
    repeatOps('+')
    print(valStack.top())

Create a class that represents the stack and use it as a global variable in the set function, which continues to initialize.

The source above is part of it. In the EvalExp function, it accumulates well in the stack variable The repeatOps function opStack.top() still says stack is empty.

I don't know if it's because it's my first time with object orientation, but whenever I set it as a global variable, I don't know if it's because it's initializing. I wonder how I can't initialize it.

The above code is a calculator using a stack.

data

2022-09-22 20:10

1 Answers

If you look at the program above, I created a Stack class and created an instance called valStack through valStack = Stack(). self currently on the valStack instance.The property called items is empty. After this Are you running EvalEXp? (FYI, it is customary to start function name with a lowercase letter from Python. If you run repeatOps, there will be no result. Because self.items are empty.

I can't give you a good answer because I don't understand the flow of the whole


2022-09-22 20:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.