返回__str __()python中的字典

时间:2016-03-19 00:52:10

标签: python class dictionary return

我从课开始,我遇到了这个问题:我想在def __str__(self)中打印一本字典,但是当我使用print时,它会给我一个错误,当我使用return时,只打印一行。你能帮帮我吗?

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]))

错误:

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)

1 个答案:

答案 0 :(得分:2)

__str__的{​​{1}}应该返回一个字符串。你可以尝试这样的事情。

ContactList

使用此方法更新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 Contact方法。 (最后添加了换行符。)

__str__