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

0 python methods class instance typeerror

class stack:
    def __init__(self):
        self.st = []
    def push(self, x):
        self.st.append(x)
        return self
    def pop(self):
        return self.st.pop()
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我为什么我不能运行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)
>>> 
Run Code Online (Sandbox Code Playgroud)

但是当我编写这段代码时,我可以毫无错误地推送到堆栈:

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
Run Code Online (Sandbox Code Playgroud)

idj*_*jaw 5

错误告诉您确切的问题:

...method push() must be called with stack instance...
Run Code Online (Sandbox Code Playgroud)

你这样做:

stack.push(3)
Run Code Online (Sandbox Code Playgroud)

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

>>> st = stack()
>>> st.push(3)
Run Code Online (Sandbox Code Playgroud)

你实际上在你的余额函数中正确地做了这个:

st = stack() #stack variable
Run Code Online (Sandbox Code Playgroud)

现在你实际上有一个实例stack.您还可以在此处的代码中明确地使用它,例如:

st.push(i)
Run Code Online (Sandbox Code Playgroud)

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

您还应该参考PEP8样式指南以遵守适当的约定.例如,类应该是大写的:stack应该是Stack