1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Python __iter__ and __repr__ what they doing?

Discussão em 'Python' iniciado por Stack, Outubro 1, 2024 às 02:23.

  1. Stack

    Stack Membro Participativo

    I am currently working on LinkedList and I have the following code and I don't understand what the __iter__ and __repr__ are doing exactly?

    class Node:
    def __init__(self, value):
    self.value = value
    self.next = None

    class LinkedList:
    def __init__(self):
    self.head = None

    def append(self, value):
    if self.head is None:
    self.head = Node(value)
    return

    node = self.head
    while node.next:
    node = node.next

    node.next = Node(value)

    def __iter__(self):
    node = self.head
    while node:
    yield node.value
    node = node.next

    def __repr__(self):
    return str([v for v in self])


    Here I am creating the LinkedList and append the values at the end of my list.

    llist = LinkedList()
    for value in [4,2,5,1,-3,0]:
    llist.append(value)


    If I print the list print(llist) then I am getting [4, 2, 5, 1, -3, 0]

    I guess this is coming from __iter__ and __repr__. What I don't understand is when my __iter__ and __repr__ starts and which is running first? How can I print objects outside my class?

    Continue reading...

Compartilhe esta Página