user6850989
user6850989

Reputation:

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()

Can someone tell me why I can't run python and do stack.push(3) without getting the unbound error. I do the following

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

But when I write this code I can push to the stack without error:

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

Upvotes: 0

Views: 76

Answers (1)

idjaw
idjaw

Reputation: 26578

The error is telling you the exact problem:

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

You are doing this:

stack.push(3)

Which is not a stack instance. You are trying to call an instance method as a class method, because you haven't instantiated stack. For example:

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

You actually did this properly in your balance function:

st = stack() #stack variable

Now you actually have an instance of stack. You also clearly use it properly further down in your code here, for example:

st.push(i)

Furthermore, you should not be calling stack a variable, it is a class.

You should also reference the PEP8 style guide to adhere to proper conventions. For example, classes should be uppercase: stack should be Stack

Upvotes: 5

Related Questions