I am a new user to python and am trying to update a class I have that is called Player(self, name, position) through a new class call API(object). In the class API(), I have the CRUD approach in creating a player, retrieving a player, updating a player, and lastly, deleting a player. I am struggling with the method in my update and delete function.
For update, I am calling self.retrieve_player[name] since it is a method that already reads the existing players from the initialized dictionary (found in the init file of class API.
Also, the main() function at the bottom is instantiating these methods by creating an instance of the object, calling API and the specified methods. e.g.:
c = API()
c.create_player('Buster Posey', 'Catcher')
c.retrieve_player('james')
c.update_player('Buster Posey', 'Firstbaseman')
The code I am struggling with is outputting an updated object that I created:
def update_player(self, name, position):
updated_player = self.retrieve_player(name)
updates = self.create_player(name, position)
updated_player = updates
return updates
print('updated now!')
def delete_player(self, name, position):
del_player = self.retrieve_player[name]
if name in del_player:
del self._team[key]
For update_player, I was playing with concept since the mentality for updating variables is something like:
a = "apple"
b = "orange"
x = a
x = b #now apple is replaced with the value orange
e.g.:
I created the player (Buster Posey, Catcher) in c.create_player. I want to update this player to reflect his new position, e.g. (Buster Posey, FirstBaseman) through the method update_player.
Afterwards, I want to delete the player altogether by using the method delete_player.
Right now, when I use the current method that is defined for update_player, I get the created_player and the updated_player... python prints: Buster Posey, Catcher Buster Posey, FirstBaseman instead of ONLY printing Buster Posey, FirstBaseman.
More code:
class Player(object):
def __init__(self, name, position):
self._name = name
self._position = position
class API(object):
playercount = 0
managercount = 0
def __init__(self):
self._team = {} #acts like a db
self._index = 0
API.playercount += 1
API.managercount += 1
##This is the CRUD method for the entity Player
def create_player(self, name, position):
new_player = Player(name, position)
self._team[self._index] = new_player
self._index += 1
print(name, position)
def retrieve_player(self, name): # need to iterate through the dictionary
for person in self._team.itervalues():
if person._name == name:
return person
print(name)
elif person._name != name:
print('Sorry, this gent does not exist.')