Return dictionary in __str__() python

I am starting with classes and i got stuck at this: I want to print out a dictionary in def __str__(self) but when I use print it gives me an error and when I use return in prints only one line. Can you help me please?

class Contact(object):

    def __init__(self, name, phone, email):
        self.name = name
        self.phone = phone
        self.email = email

    def __str__(self):
        return "{} {} {}".format(self.name, self.phone, self.email)

class ContactList(object):

    def __init__(self, d={}):
        self.d = d

    def add_contact(self, n):
        self.d[n.name] = [n.phone, n.email]

    def del_contact(self, n):
        self.d[n] = 0
        del self.d[n]

    def get_contact(self, n):
        if n in self.d:
            return '{} {} {}'.format(n, self.d[n][0], self.d[n][1])
        else:
            return '{}: No such contact'.format(n)

    def __str__(self):
        print('Contact list')
        print('------------')
        for key in sorted(self.d.items()):
            print(Contact(key[0], key[1][0], key[1][1]))

The error:

Traceback (most recent call last):
  File "contacts_72.py", line 58, in <module>
    main()
  File "contacts_72.py", line 51, in main
    print(cl)
TypeError: __str__ returned non-string (type NoneType)

Upvotes: 0

Views: 6423

Answers (1)

Vivek Pabani
Vivek Pabani

Reputation: 452

The __str__ of ContactList should return a string. You may try something like this.

def __str__(self):
    c_list = 'Contact list\n' + '------------\n'
    for key, value in sorted(self.d.items()):
        c_list += str(Contact(key, value[0], value[1]))
    return c_list

Update the Contact class __str__ method with this. (just added newline char at the end.)

def __str__(self):
    return "{} {} {}\n".format(self.name, self.phone, self.email)

Upvotes: 2

Related Questions