[英]Trying to recreate a __str__() method in python
I have been tasked with trying to recreate the methods of an ArrayList type for python.我的任务是尝试为 python 重新创建 ArrayList 类型的方法。 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.我已经成功地重新创建了除 str 和 repr 函数之外的所有内容,但由于它们的行为大致相同,因此我只需要一个帮助。 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方法: lst[i] 用于在现有的正索引 i 处获取和设置值
len(lst) to obtain the number of slots len(lst) 获取槽数
lst.append(None) to grow the list by one slot at a %time lst.append(None) 以 % 时间将列表增加一个槽
del lst[len(lst)-1] to delete the last slot in a list del lst[len(lst)-1] 删除列表中的最后一个槽
The key is that you can use str()
on the elements of the list;关键是你可以在列表的元素上使用str()
; since your __str__()
isn't calling str(self)
, you won't have infinite recursion.由于您的__str__()
没有调用str(self)
,因此您不会有无限递归。
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))) + ']'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.