模块没有属性“推”

时间:2018-03-03 20:21:40

标签: python python-2.7 class methods python-2.x

我正在尝试将元素添加到另一个文件的堆栈中,但我遇到了错误。

这是我要导入的课程:

class Empty(Exception): 
    """Error attempting to access an element from an empty container.""" 
    pass

class Stack_PlistLR: 
    def __init__ (self): 
        """Create an empty stack.""" 
        self._data = [ ] # nonpublic list instance 

    def __len__(self): 
        """Return the number of elements in the stack."""
        return len(self._data)

    def isEmpty(self): 
        """Return True if the stack is empty.""" 
        return len(self._data) == 0

    def push(self, e): 
        """Add element e to the top of the stack.""" 
        self._data.append(e)    # new item stored at end of list

    def top(self): 
        """Return (but do not remove) the element at the top of the stack. Raise Empty exception if the stack is empty. """ 
        if self.isEmpty():
            raise Empty('Stack is empty') 
        return self._data[-1] # the last item in the list

    def pop(self): 
        """Remove and return the element from the top of the stack (i.e., LIFO). Raise Empty exception if the stack is empty. """ 
        if self.isEmpty():
            raise Empty("Stack is empty") 
        return self._data.pop( )    # remove last item from list


    def __str__(self):
        str_s = ""

        for e in self._data:
            str_s+=str(e)+" "

        return str_s.strip()    

我目前的代码:

import Stack_PlistLR as s2

s2.push(14)
print(s2)

我收到错误消息:

  

AttributeError:模块'Stack_PlistLR'没有属性'push'

显然这个类有push属性?我该如何解决这个问题?

4 个答案:

答案 0 :(得分:2)

这里有两件事情,看起来像是:

  1. 从您的import语句中,您可以在模块Stack_PlistLR内找到名为Stack_PlistLR.py的类。
  2. 您需要实例化类的实例,而不是仅仅引用没有实例化的方法,就像现在一样。
  3. 即:

    from Stack_PlistLR import Stack_PlistLR
    
    s2 = Stack_PlistLR()
    s2.push(14)
    print(s2)
    

答案 1 :(得分:2)

您正在将文件Stack_PlistLR导入为s2。现在s2有Stack_PlistLR和Empty clases。

你可以通过print(dir(s2))来看到它

<Card>

如果要使用s2的Stack_PlistLR。你应该instatiate和Stack_PlistLR然后使用它。这是一段代码:

['Empty', 'Stack_PlistLR', '__builtins__', '__cached__', '__doc__', 
'__file__', '__loader__', '__name__', '__package__', '__spec__']

答案 2 :(得分:1)

创建该类的实例,然后在该实例上调用.push()

您可以从方法标题中看到,它接受self作为参数。这意味着它需要一个实例来执行

def push(self, e): 

您的代码如下:

from Stack_PlistLR import Stack_PlistLR
s2 = Stack_PlistLR()
s2.push(14)
print(s2)

答案 3 :(得分:0)

班级不是模块。它是模块命名空间中的一个对象,因此如果您已将模块导入为s2,那么它将在您的程序中为s2. Stack_PlistLR