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

时间:2016-11-02 00:11:11

标签: python class methods 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()

有人能告诉我为什么我不能运行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

1 个答案:

答案 0 :(得分:5)

错误告诉您确切的问题:

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

你这样做:

stack.push(3)

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

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

您实际上已在平衡功能中正确执行此操作:

st = stack() #stack variable

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

st.push(i)

此外,您不应该将stack称为变量,而是

您还应该引用PEP8 style guide以遵守适当的约定。例如,类应为大写:stack应为Stack