If I try to print the class variable which is a list, I get a Python object. (These are examples I found on stackoverflow).
class Contacts:
all_contacts = []
def __init__(self, name, email):
self.name = name
self.email = email
Contacts.all_contacts.append(self)
def __str__(self):
return '%s, <%s>' % (self.name, self.email)
c1 = Contacts("Grace", "[email protected]")
print(c1.all_contacts)
[<__main__.Contact object at 0x0287E430>, <__main__.Contact object`
But in this more simple example, it actually prints:
class Example():
samplelist= [1,2,3]
test= Example()
print (test.samplelist)
[1, 2, 3]
I figured this line is the culprit: Contact.all_contacts.append(self)
in the first sample code. But I'm not exactly sure whats going on here.
EDIT:
Several users told me to just append self.name
instead of just self
.
So when I do this:
class Contacts:
all_contacts = []
def __init__(self, name, email):
self.name = name
self.email = email
Contacts.all_contacts.append(self.name)
Contacts.all_contacts.append(self.email)
def __str__(self):
return '%s, <%s>' % (self.name, self.email)
def __repr__(self):
return str(self)
c1 = Contacts("Paul", "[email protected]")
c2 = Contacts("Darren", "[email protected]")
c3 = Contacts("Jennie", "[email protected]")
print(Contacts.all_contacts)
I get:
['Paul', '[email protected]', 'Darren', '[email protected]', 'Jennie', '[email protected]']
Instead of:
[Paul, <[email protected]>, Darren, <[email protected]>, Jennie, <[email protected]>]
Thus, the formatting in the __str__
method isn't working here.