[英]Return dictionary in __str__() python
我是从类开始的,我对此深陷其中:我想在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)
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
__str__
更新Contact
类__str__
方法。 (只需在末尾添加换行符。)
def __str__(self):
return "{} {} {}\n".format(self.name, self.phone, self.email)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.