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", "something@hotmail.com")
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", "something@hotmail.com")
c2 = Contacts("Darren", "another_thing@hotmail.com")
c3 = Contacts("Jennie", "different@hotmail.com")
print(Contacts.all_contacts)
I get:
['Paul', 'something@hotmail.com', 'Darren', 'another_thing@hotmail.com', 'Jennie', 'different@hotmail.com']
Instead of:
[Paul, <something@hotmail.com>, Darren, <another_thing@hotmail.com>, Jennie, <different@hotmail.com>]
Thus, the formatting in the __str__
method isn't working here.