Search code examples
pythonpython-3.xstringkeyword-argument

Correct usage of __str__ method for a dictionary (kwargs)


I have a task to print correctly kwargs arguments of a class.

Here is my code:

 class Contact:
        def __init__(self, name, surname, number, selected=None, **kwargs):
            self.name=name
            self.surname=surname
            self.number=number
            self.selected=selected
            self.additional=kwargs
        def __str__(self):
            if self.selected==None:
                selected='No'
            else:
                selected='Yes'
            return 'Name: ' + self.name+'\n' + \
                   'Surname: ' + self.surname+ '\n' + \
                   'Phone: ' + self.number + '\n' + \
                   'In selected: ' + selected + '\n' + \
                   'Additional information: ' + '\n' + \
                   str(self.additional.keys()) + '\n' + \
                   str(self.additional.values())
         
    if __name__=='__main__':
        jhon = Contact('Jhon', 'Smith', '+71234567809', telegram='@jhony', email='jhony@smith.com')
        print (jhon)

I need to have in the end:

Additional information:
     telegram : @jhony
     email : jhony@smith.com

But all I've got is :

enter image description here

I've really tried to iterate over it, create lists, and I've got nothing, because the ___str___ method could only use str objects. How can I go through the kwargs arguments and take it in format of key : value?


Solution

  • You need to iterate over the dict referenced by self.additional.

    def __str__(self):
        return ('Name: ' + self.name + '\n'
                + 'Surname: ' + self.surname+ '\n' + 
                + 'Phone: ' + self.number + '\n' +
                + 'In selected: ' + selected + '\n' +
                + 'Additional information: ' + '\n' + 
                + '\n'.join([f'     {k}: {v}' for k, v in self.additional.items()]))