How do I print the actual contents of this list
The code is short and simple:
class Contact:
all_contacts = 开发者_开发问答[]
def __init__(self, name, email):
self.name = name
self.email = email
Contact.all_contacts.append(self)
c1 = Contact("Paul", "something@hotmail.com")
c2 = Contact("Darren", "another_thing@hotmail.com")
c3 = Contact("Jennie", "different@hotmail.com")
for i in Contact.all_contacts:
print(i)
Clearly all I want to do is print the 'all_contacts' list with the info I have added, but what I get is:
<__main__.Contact object at 0x2ccf70>
<__main__.Contact object at 0x2ccf90>
<__main__.Contact object at 0x2ccfd0>
What am I doing wrong?
Add the following to your Contact class:
class Contact:
...
def __str__(self):
return '%s <%s>' % (self.name, self.email)
This will tell Python how to render your object in a human-readable string representation.
Reference information for str
The __repr__
and __str__
methods for Contact
aren't defined, so you get this default string representation instead.
def __str__(self):
return '<Contact %s, %s>' % (self.name, self.email)
Separate the container from the items stored in the container.
Add a
__str__()
method toContact
.class Contact: def __init__(self, name, email): self.name = name self.email = email def __str__(self): return "{} <{}>".format(self.name, self.email) class ContactList(list): def add_contact(self, *args): self.append(Contact(*args)) c = ContactList() c.add_contact("Paul", "something@hotmail.com") c.add_contact("Darren", "another_thing@hotmail.com") c.add_contact("Jennie", "different@hotmail.com") for i in c: print(i)
精彩评论