为什么调用此方法会出现错误 "Unbound method ... instance as first arg"?

Why is calling this method giving error "Unbound method ... instance as first arg"?

class stack:
    def __init__(self):
        self.st = []
    def push(self, x):
        self.st.append(x)
        return self
    def pop(self):
        return self.st.pop()

有人能告诉我为什么我不能 运行 python 并执行 stack.push(3) 而不会出现未绑定错误。我执行以下操作

>>> from balance import *
>>> stack.push(3)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: unbound method push() must be called with stack instance as first argument (got int instance instead)
>>> 

但是当我写这段代码时,我可以毫无错误地压入堆栈:

import sys

k = sys.argv[1]

class stack:
    def __init__(self):
        self.st = []
    def push(self, x):
        self.st.append(x)
        return self
    def pop(self):
        return self.st.pop()
    def isEmpty(self):   #added an empty fucntion to stack class
        return self.st == []

def balance(k):
    braces = [ ('(',')'), ('[',']'), ('{','}') ] #list of braces to loop through
    st = stack() #stack variable

    for i in k:   #as it iterates through input 
              #it checks against the braces list
        for match in braces:
            if i == match[0]:  #if left brace put in stack
                st.push(i)
            elif i == match[1] and st.isEmpty():  #if right brace with no left
                st.push(i)                        #append for condition stateme$
            elif i == match[1] and not st.isEmpty() and st.pop() != match[0]:
                st.push(i)   #if there are items in stack pop
                         # for matches and push rest to stack

if st.isEmpty(): #if empty stack then there are even braces
    print("Yes")
if not st.isEmpty():  #if items in stack it is unbalanced
    print("No")


balance(k) #run balance function

错误告诉您确切的问题:

...method push() must be called with stack instance...

您正在这样做:

stack.push(3)

不是堆栈实例。您正在尝试将实例方法作为 class 方法调用,因为您尚未实例化 stack。例如:

>>> st = stack()
>>> st.push(3)

您实际上在平衡函数中正确地做到了这一点:

st = stack() #stack variable

现在您实际上拥有了 stack 的一个实例。您还 清楚地 在此处的代码中进一步正确使用它,例如:

st.push(i)

此外,你不应该调用 stack 一个变量,它是一个 class.

您还应该参考 PEP8 style guide 以遵守适当的约定。例如,classes 应该是大写的:stack 应该是 Stack