How to print this class variable?

If I try to print a class variable, which is a list, I get a Python object. (These are the examples I found in 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 simpler example, it does print:

class Example():
    samplelist= [1,2,3]

test= Example()
print (test.samplelist)
[1, 2, 3]

I realized that this line is the culprit: Contact.all_contacts.append(self)in the first code example. But I'm not quite sure what is going on here.

EDIT:

Several users told me to simply add self.nameinstead 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:

[Paul, <something@hotmail.com>, Darren, <another_thing@hotmail.com>, Jennie, <different@hotmail.com>]

Thus, formatting in a method __str__does not work here.

+4
source share
3 answers

, __str__ , __repr__() . __repr__() . -

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)

    def __repr__(self):
        return str(self)

-

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)

    def __repr__(self):
        return str(self)

contact1 = Contacts("Grace1", "something1@hotmail.com")
contact2 = Contacts("Grace2", "something2@hotmail.com")
contact3 = Contacts("Grace3", "something3@hotmail.com")
print(Contacts.all_contacts)

-

[Grace1, <something1@hotmail.com>, Grace2, <something2@hotmail.com>, Grace3, <something3@hotmail.com>]

, , 6, , __repr__.

+12

, :

Contacts.all_contacts.append(self)

self all_contacts.

- , - all_contacts.

+3

python str (all_contacts), .

python .

+2

Source: https://habr.com/ru/post/1609750/


All Articles