0

For the sake of knowledge, I would like to print the contents of the class attribute list all_contacts of this code:

class Contact:
    all_contacts = []

    def __init__(self,name,email):
        self.name = name
        self.email = email
        Contact.all_contacts.append(self)

However, all my attempts result in a memory address:

>>> c = Contact("Some Body", "somebody@example.net")
>>> c2 = Contact("Some Body 2", "somebody2@example.net")

>>> Contact.all_contacts
[<__main__.Contact object at 0x0000000002C8CF48>]

>>> print(Contact.all_contacts)
[<__main__.Contact object at 0x0000000002C8CF48>]

>>> c.all_contacts
[<__main__.Contact object at 0x0000000002C8CF48>]

How do I print this class attribute so I can see it's elements?

Steffo
  • 305
  • 5
  • 13
Flonne
  • 91
  • 8
  • 1
    You are printing it. You added `self` to `all_contacts`, and `Contact`, when printed is `<__main__.Contact object at 0x0000000002C8CF48>` because you didn't define a `__str__` or `__repr__` for `Contact`. Note the `[]` around the output indicating that it's printing a list. – Carcigenicate Jan 05 '20 at 17:42

1 Answers1

3

You just need to implement __repr__() as required:

class Contact:
    all_contacts = []

    def __init__(self, name, email):
        self.name = name
        self.email = email
        Contact.all_contacts.append(self)
    def __repr__(self):
        return f"Name:{self.name} Email:{self.email}"

c = Contact("Some Body", "somebody@example.net")
c2 = Contact("Some Body 2", "somebody2@example.net")

print( Contact.all_contacts)

Output:

[Name:Some Body Email:somebody@example.net, Name:Some Body 2 Email:somebody2@example.net]
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 2
    If you are using Python 3.8+, you can use the following f-string to get the same output while writing less code: `` – Steffo Jan 05 '20 at 17:51