1

im a beginner in python and don't understand the following: i define a class and a list. When I want to print the list after appending it, I don't get strings, although I have a method that should return me a string, right? I don't see what is wrong here.. :/ I would expect the outcome to be [14,12]... If someone knows what I did wrong, please tell me :/

class av:

    def __init__(self, num):
        self.num = num
    def __str__(self,num):
        self.num = num
        return str(self.num)

lst = []

lst.append(av(14))

lst.append(av(12))

print(lst)

outcome:

[<__main__.av object at 0x102503dd0>, <__main__.av object at 0x102505d90>]
AMC
  • 2,642
  • 7
  • 13
  • 35
blust bibi
  • 27
  • 1

2 Answers2

6

__str__ is only used when you print objects, you can use __repr__ to get a convenient "representation" on the console (more details):

>>> class av:
...     def __init__(self, num):
...         self.num = num
...     def __str__(self):
...         return str(self.num)
...     def __repr__(self):
...         return 'av(%d)' % self.num
... 
>>> av(12)
av(12)
>>> print(av(12))
12
>>> [av(12), av(12)]
[av(12), av(12)]
>>> print([av(12), av(12)])
[av(12), av(12)]
BlackBear
  • 22,411
  • 10
  • 48
  • 86
0

First, your str method has some redundancies. It should look like:

def __str__(self):
    return str(self.num)

The str method shouldn't really take any parameters other than 'self', and self.num = num is already declared in your init method, so it isn't doing anything.

As for printing, when you append your objects to your list, what it actually contains is now a list of "pointers", or references to the locations in memory where your object data is stored. So when you try to print out the list it simply returns the pointer to those locations in memory written as: object of class av in the main file, and then a hex code representing the memory location. The str method only works if you are referencing the actual "pointer" (the object itself). So if you wanted to print out the self.num value in your list, you could iterate through it using a for loop:

for obj in lst:
    print(obj)

This way you're printing the object directly. If you wanted them on the same line, just change it to: print(obj, end = '')