Some way to return a list using Python classes

3

I'm doing a small example with classes in Python but I want you to print a list of elements so use __str__ but I mark the error that it was not a type string here is my code:

class intSet(object):
    def __init__(self):
        self.vals = []
    def insert(self, e):
        if e not in self.vals:
            self.vals.append(e)
    def __str__(self):
        return self.vals

s = intSet()
s.insert(1)
s.insert(4)
s.insert(6)
print(s)

Is there a function that returns a list?

    
asked by Luis Miguel 12.07.2017 в 18:40
source

1 answer

3

Returning a list is as simple as you are doing, the only problem is that __str__ is a very special method and it is used to "customize" the created object. Particularly __str__ defines how a common str() will work on the object. As str() is forced to return a string and in your example the print(s) implicitly invokes str() , what you should do is:

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

Or you can eventually configure the __repr__ method, which is more comprehensive already used if you do not have __str__ .

def __repr__(self):
    return str(self.vals)

I add an important clarification, both __str__ as __repr__ are functions that serve to generate a representation let's say that "graphic" type chain of the object, in your example we choose the simplest way to represent the object: a simple str of a list, but the representation is to the liking of the author or according to the complexities of the object, the important thing is that the return is always a chain.

    
answered by 12.07.2017 / 18:59
source