【问题标题】:Why is calling this method giving error "Unbound method ... instance as first arg"?为什么调用此方法会给出错误“未绑定方法...实例作为第一个参数”?
【发布时间】:2017-03-15 05:01:51
【问题描述】:
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

【问题讨论】:

  • 总是用 MixedCase 命名一个 class,用小写命名一个 instance,正如 idjaw 和 PEP-8 所说。那么你就不能像你在这里所做的那样把一个类和一个实例混为一谈了。

标签: python class methods instance typeerror


【解决方案1】:

错误告诉你确切的问题:

...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

【讨论】:

  • 谢谢。我们的教授从未告诉我们为类或函数创建变量是在实例化任何东西。以为是
  • 认为这是人们所做的事情。谢谢你澄清这一切。
猜你喜欢
  • 1970-01-01
  • 2014-04-15
  • 1970-01-01
  • 2014-09-10
  • 2014-12-10
  • 2013-12-31
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
相关资源
最近更新 更多