【发布时间】: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