Format an object print

Asked

Viewed 74 times

0

Time, I need to format the print of the following class:

class Tupla:

def __init__(self, keys, palavras):
    self.keys = list(keys)
    self.palavras = list(palavras)
    self.op = dict(zip(self.keys, self.palavras))

def __getitem__(self, key):
    return self.op[key]

def __repr__(self):
    return f'Tabela Completa: {self.op}'

def get_tupla(self, key):
    return f'Palavra: {self.op[key]}'

I believe in the method:

    def __repr__(self):
    return f'Tabela Completa: {self.op}'

I wanted the result to be (For each of the elements of the dictionary):

Key:   | Palavra:  

Second stage of the question:

    def get_pagina(self, num):
    to_print = "Key:\t| Palavra:\n"
    for item in self.paginas[num]:
        to_print += str(item) + "\t\t  " + str(self.paginas[item]) + "\n"
    return to_print

Where:

    aux = list(zip(keys, palavras))
    self.paginas = list()

1 answer

3


To change what will appear when you pass the object to the print() method, you must override the method __str__() of the object and return a string.

class Tupla:

    def __init__(self, keys, palavras):
        self.keys = list(keys)
        self.palavras = list(palavras)
        self.op = dict(zip(self.keys, self.palavras))

    def __getitem__(self, key):
        return self.op[key]

    def __repr__(self):
        return f'Tabela Completa: {self.op}'

    def get_tupla(self, key):
        return f'Palavra: {self.op[key]}'

    def __str__(self):
        to_print = "Key:\t| Palavra:\n"
        for item in self.op:
            to_print += str(item) + "\t\t  " + str(self.op.get(item)) + "\n"
        return to_print


t = Tupla(keys=(1, 2, 3, 4, 5), palavras=("um", "dois", "tres", "quatro", "cinco"))
print(t)
  • Renan, that’s exactly what it was, obg ! But trying to reproduce your example, I hit another error but this time in a second class, have a look ? I edited the question.

  • I’m sorry, I just started programming...

  • What mistake is happening and what you hoped was happening?

  • Well I wanted to print a specific page: Page: {num} | Words: {}

  • When you do self.pages[num] returns a list of words on that page? If so, start the string with to_print = "Key: {} t | Word: ". format(num) and inside for you will add the words to_print += str(item) + " "

Browser other questions tagged

You are not signed in. Login or sign up in order to post.