【发布时间】: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