2016-11-02 2 views
0
class stack: 
    def __init__(self): 
     self.st = [] 
    def push(self, x): 
     self.st.append(x) 
     return self 
    def pop(self): 
     return self.st.pop() 

누군가 파이썬을 실행할 수없고 언 바운드 오류가 발생하지 않고 stack.push (3)을 실행할 수없는 이유를 말해 줄 수 있습니까? 내가 수행이 메서드를 호출하면 "Unbound method ... instance as first arg"오류가 발생하는 이유는 무엇입니까?

>>> 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 
+0

이어야합니다. idjaw 및 PEP-8처럼 MixedCase 및 ** 인스턴스 **는 소문자로 항상 ** 클래스 **로 지정하십시오. 그런 다음 여기에서 하듯이 클래스를 인스턴스와 혼동 할 수 없습니다. – smci

답변

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을 참조해야합니다. 예를 들어, 클래스는 대문자 여야합니다. stackStack

+0

고맙습니다. 교수님은 클래스 또는 함수에 대한 변수를 만드는 것이 무엇이든 인스턴스화한다고 말한 적이 없습니다. 그렇다고해도 –

+0

사람들이 한 일이라고 생각했습니다. 모든 내용을 명확히 해 주셔서 감사합니다. –