简体   繁体   中英

Trying to recreate a __str__() method in python

I have been tasked with trying to recreate the methods of an ArrayList type for python. I have been successful in recreating everything except for the str and the repr function, but since they behave mostly the same I only need help with one. Below is my code for the method, but I keep getting a Type Error stating "can only join an iterable"

def __str__(self):
    """Implements `str(self)`. Returns '[]' if the list is empty, else
    returns `str(x)` for all values `x` in this list, separated by commas
    and enclosed by square brackets. E.g., for a list containing values
    1, 2 and 3, returns '[1, 2, 3]'."""
    str= '['
    if len(self.data)>0:
        for i in range(len(self.data)):
            if i ==0:
                str1 = str+''.join(self[i])
            else:
                str1 = str+','+ ''.join(self[i])
        return str1+']'
    else:
        return '[]'

There is just one catch to all of this, and that is that I can only call the following methods to help, though this should not be a limitation for this method. Please Help!

Methods: lst[i] for getting and setting a value at an existing, positive index i

len(lst) to obtain the number of slots

lst.append(None) to grow the list by one slot at a %time

del lst[len(lst)-1] to delete the last slot in a list

The key is that you can use str() on the elements of the list; since your __str__() isn't calling str(self) , you won't have infinite recursion.

Here is one way to do it.

#UNTESTED
def __str__(self):
    """Implements `str(self)`. Returns '[]' if the list is empty, else
    returns `str(x)` for all values `x` in this list, separated by commas
    and enclosed by square brackets. E.g., for a list containing values
    1, 2 and 3, returns '[1, 2, 3]'."""

    # Assuming that SELF implements iteration
    return '[' + ', '.join(str(x) for x in self) + ']'

    # Assuming that iteration isn't implemented
    return '[' + ', '.join(str(self[i]) for i in range(len(self))) + ']'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM