【问题标题】:Return dictionary in __str__() python在 __str__() python 中返回字典
【发布时间】:2016-07-05 22:16:31
【问题描述】:

我从课程开始,但我陷入了困境:我想在def __str__(self) 中打印出一本字典,但是当我使用 print 时它会给我一个错误,而当我使用 return in 时只打印一行。你能帮帮我吗?

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)

【问题讨论】:

  • 在我看来,您返回的任何字典都不像...
  • 因为str是函数,不是过程,所以必须返回值才能显示。
  • 你想要"{}\n{}\n{}".format(...) 代替吗?
  • 我想返回字典中的所有条目,但是当我使用 return 时它只返回 1
  • 请在您的问题中添加 Traceback。

标签: python class dictionary return


【解决方案1】:

ContactList__str__ 应该返回一个字符串。你可以试试这样的。

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__ 方法。 (只是在末尾添加了换行符。)

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

【讨论】:

  • 天哪,这真的很接近,但可以在每一行放置一个条目吗?
  • 将 Contact 类的 str 方法更新为已编辑的答案。 (只是在末尾添加了换行符。)
猜你喜欢
  • 2017-08-25
  • 2016-11-30
  • 1970-01-01
  • 2015-03-01
  • 1970-01-01
  • 2015-05-08
  • 2017-09-19
  • 2017-05-07
  • 2020-05-22
相关资源
最近更新 更多