0

I have the following python code:

    if direction == 0: # Left
        moved = self.slideLeft()
    elif direction == 1: # Right
        moved = self.slideRigth()
    elif direction == 2: # Up
        moved = self.slideUp()
    elif direction == 3: # Down
        moved = self.slideDown()


    if(moved):

I know there is no swith statement in python but i am curious if there maybe is a nicer way to write this. Btw moved is just a Boolean

Cing
  • 806
  • 1
  • 11
  • 29
  • 1
    maybe create a `list` of these methods (or `dict`) and use the index (or key) like `moved = mylist[1]()` would be equivalent to `moved = self.slideRight()` – Sid Vishnoi Apr 04 '18 at 19:22
  • A thank you if will do that – Cing Apr 04 '18 at 19:59
  • Do you might know if your way is faster? – Cing Apr 04 '18 at 20:05
  • 1
    [ self.slideLeft, self.slideRight, self.slideUp, self.slideDown ][ direction ]() would work without a dictionary for your specific use case. In fact, you could create an array of movement functions in the class and use it directly: self.slide[ direction ]() – Alain T. Apr 05 '18 at 02:14
  • 1
    @Cing no idea if it's faster. haven't tested. if you have just 4 functions, and aren't calling them very often, performance shouldn't be an issue. Make sure you (and your team) use the one that is more readable :) – Sid Vishnoi Apr 05 '18 at 16:27

0 Answers0