[英]Why the function of class call the attribute error
我是新手所以提前谢谢你
class stack():
def __init__(self):
self._stack = []
def push1(self, item):
self._stack.append(item)
import test1
a = test1.stack()
a.push1(5)
在此代码中,当在命令提示符中写入上面的内容以及 test1 模块中的代码本身时,它可以工作
class StackEmptyException(Exception):
pass
class my_stack:
def __init__(self):
self._stack = []
def check_input_type(inp):
if not isinstance(inp, my_stack):
raise TypeError('Expected stack; got %s' % type(inp).__name__)
def push(item, st:my_stack):
check_input_type(st)
st._stack.append(item)
def push1(self, item):
self._stack.append(item)
def pop(st:my_stack):
check_input_type(st)
to_return = None
try:
to_return = st._stack[-1]
st._stack = st._stack[:-1]
except IndexError:
raise StackEmptyException("Stack is empty") from None
return to_return
def top(st:my_stack):
check_input_type(st)
to_return = None
try:
to_return = st._stack[-1]
except IndexError:
raise StackEmptyException("Stack is empty") from None
return to_return
def is_empty(st:my_stack):
check_input_type(st)
return len(st._stack) == 0
def create_stack():
return my_stack()
但是在这段代码中,当我尝试做同样的事情时它会抛出错误
import my_stack
a = my_stack.my_stack()
a.push1(5)
AttributeError: 'my_stack' object 没有属性 'push1'
在代码的第二部分我不明白为什么在某些函数参数中有 st:my_stack() 如何工作我也可以替换它
代码在 my_stack 模块中
正如其他人提到的,您需要缩进 push1 以便 Python 知道它是您的my_stack
class 的属性
class my_stack:
def __init__(self):
self._stack = []
#Notice push1 is indented
def push1(self, item):
self._stack.append(item)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.