Метод, действующий как атрибут с Node и LinkedStack - PullRequest
0 голосов
/ 10 октября 2018

Итак, я переписываю класс Node, чтобы встроить методы доступа и мутатора, а затем я собираюсь изменить класс LinkedStack, чтобы включить методы.Прямо сейчас я написал методы в Node, но я изменил взгляд в LinkedStack, и я получаю эту ошибку:

AttributeError: 'Node' object has no attribute 'getdata' 

Я пытаюсь использовать getdata () в качестве методане атрибут.Я думал, что () будет сигнализировать, что это метод.

class Node(object):

    def __init__(self, data, next = None):
        """Instantiates a Node with default next of None"""
        self.data = data
        self.next = next

    #Accessors   
    def getdata(self):
        return self.data

    def getnext(self):
        return self.next

    #Mutators
    def setdata(self, item):
        self.data = item

    def setnext(self, pointer):
        self.next = pointer

class LinkedStack(object):
    """ Link-based stack implementation."""

    def __init__(self):
        self._top = None
        self._size = 0

    def push(self, newItem):
        """Inserts newItem at top of stack."""
        self._top = Node(newItem, self._top)
        self._size += 1

    def pop(self):
        """Removes and returns the item at top of the stack.
        Precondition: the stack is not empty."""
        oldItem = self._top.data
        self._top = self._top.next
        self._size -= 1
        return oldItem

    def peek(self):
        """Returns the item at top of the stack.
        Precondition: the stack is not empty."""
        return self._top.getdata()  #This is the thing that's acting like an attribute...

    def __len__(self):
        """Returns the number of items in the stack."""
        return self._size

    def isEmpty(self):
        return len(self) == 0

    def __str__(self):
        """Items strung from bottom to top."""

        # Helper recurses to end of nodes
        def strHelper(probe):
            if probe is None:
                return ""
            else:
                return strHelper(probe.next) + \
                    str(probe.data) + " "

        return strHelper(self._top)

def main():
    # Test implementation
    s = LinkedStack()
    print "Length:", len(s)
    print "Empty:", s.isEmpty()
    print "Push 1-10"
    for i in xrange(10):
        s.push(i + 1)
    print "Peeking:", s.peek() 
    print "Items (bottom to top):",  s
    print "Length:", len(s)
    print "Empty:", s.isEmpty()
    print "Push 11"
    s.push(11)
    print "Popping items (top to bottom):",
    while not s.isEmpty(): print s.pop(),
    print "\nLength:", len(s)
    print "Empty:", s.isEmpty()
main()

Извините, что много кода, чтобы прочесать ...

...