3

I was wondering if there was a way to have a variable value as part of another variable name in python. I have my code here, but I think there should be a way to make it a lot cleaner:

if self.player.dir == 'UP':
    self.player.image = self.player.image_up[0]
if self.player.dir == 'DOWN':
    self.player.image = self.player.image_down[0]
if self.player.dir == 'LEFT':
    self.player.image = self.player.image_left[0]
if self.player.dir == 'RIGHT':
    self.player.image = self.player.image_right[0]

I was thinking if we could have the value of dir as part of the self.player.image_(dir)[0]. I am not sure how I would do this though. It would look something like this I think:

self.player.image = self.player.image_(dir)[0]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174

2 Answers2

4

something like this might be what you are looking for:

images = {
    "UP": self.player.image_up[0],
    "DOWN": self.player.image_down[0],
    "RIGHT": self.player.image_right[0],
    "LEFT": self.player.image_left[0]
}

self.player.image = images[self.player.dir]
Almog-at-Nailo
  • 1,152
  • 1
  • 4
  • 20
2

Using Python dictionary might be what you re looking for

self.player.image_ = {
     'UP':self.player.image_up[0],
     'DOWN': self.player.image_down[0],
     'LEFT':self.player.image_left[0],
     'RIGHT': self.player.image_right[0]
}
self.player.image = self.player.image_[self.player.dir]
3UX1N3
  • 21
  • 1