开发者

How do I print the actual contents of this list

开发者 https://www.devze.com 2023-02-18 11:07 出处:网络
The code is short and simple: class Contact: all_contacts = 开发者_开发问答[] def __init__(self, name, email):

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)


  1. Separate the container from the items stored in the container.

  2. Add a __str__() method to Contact.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号