I'm still wrestling with classes. Instead of using the classic employees in a company or car example, I've decided to create a simple game character. So far so good, only I'm having trouble adding to an item to a list which is a class.
class Player():
def __init__(self, name, items):
self.name = name
self.items = items
# initialize character
player = Player("Joey",
["movie stub", "keys", "army man"])
print(player.items)
# >> ['movie stub', 'keys', 'army man'] # this is fine
Now I'd like to add an item to the player character.
player.items.push("a rock")
# AttributeError: 'list' object has no attribute 'push'
I was trying using push - only that results in an attribute error. So I added a simple helper class:
# helper class
class List(list):
def push(self, x):
self.append(x)
player.items = List(["a rock"])
Yay! no errors...
print(player.items)
>> ['a rock']
Only instead of appending, it's replaced the list, which is not what I'm after.
Any ideas where I'm going wrong?
insert(index)– inserts a single element anywhere in the list.append()– always adds items (strings, numbers, lists) at the end of the list.extend()– adds iterable items (lists, tuples, strings) to the end of the list.appendby the namepushinstead of just usingappenddirectly? I know it's calledpushin other languages, but you're not writing those languages; trying to write code from language X in language Y leads to terrible code (all the people who come from C and only writeforloops overranges, the people who come from Perl and never usestrmethods, just theremodule, etc.). Your original problem would not be an issue if you were willing to just typeplayer.items.append("a rock").