Reputation: 73
I am trying to emulate a Java toString method I learned a while back. I might be off base here and there may definitely be an easier way to do what I'm trying to do with a simple list.
What I really want to do is be able to append objects to a list, and then print specific traits about those objects from the list. I also want to keep track of the index of the object. Here is what I have so far, but when I print, I get no errors, and a blank line, nothing prints.
class Character_list():
def __init__(self, list):
self.list = []
def toString(self):
result = ""
for i in self.list:
result += self.list[i]
return result
def main():
x = Character_list([1, 2])
print(x.toString())
main()
Upvotes: 0
Views: 7823
Reputation: 73460
Three things:
First, use the parameter you pass to the constructor to actually instantiate your object
class Character_list():
def __init__(self, lst):
self.lst = lst # use the parameter! And don't use 'list' as a variable name
# or even better, use a shallow copy:
self.lst = list(lst)
Second, python loops are generally for-each loops. That means you are iterating elements, not indexes. So
for i in self.lst:
result += i
will actually append the list elements (which have to be strings, otherwise use: result += str(i)
) to result
.
Third, Python's version of toString
is __str__
and is implicitly called when using the the built-in str()
on an object. So, for instance
def __str__(self):
return ''.join(map(str, self.lst))
will do what you intended, but more generally, e.g. when you call
print(x)
Upvotes: 5