3
from enum import Enum

class Direction(Enum):
    NORTH = 0
    EAST = 1
    SOUTH = 2
    WEST = 3

    def turn_right(self):
        self = Direction((self.value + 1) % 4)

d = Direction.EAST
print(d)
d.turn_right()
print(d)
d.turn_right()
print(d)

Intended output is supposed to be

Direction.EAST
Direction.SOUTH
Direction.WEST

after each turn, but what I got instead was just

Direction.EAST
Direction.EAST
Direction.EAST

Looks like it's not updating self, but why? How can I change the class such that its usage stays the same?

One possible workaround is

    def turn_right(self):
        return Direction((self.value + 1) % 4)

but this returns a new Direction everytime, is there a way to make the method work "in-place"?

jitiqexo
  • 31
  • 2
  • 1
    Firstly, `dir` is a built-in keyword don't use it as a variable name. Secondly, your variable is an integer and immutable, if you want to have a mutable object you better use one but in this case your logic isn't right, why you need to change the variable in-place while you can simply reassign it? – Mazdak Dec 09 '19 at 11:45
  • 1
    see https://stackoverflow.com/a/1216361/12158779 – brj Dec 09 '19 at 11:49
  • Does this answer your question? [Is it safe to replace a self object by another object of the same type in a method?](https://stackoverflow.com/questions/1216356/is-it-safe-to-replace-a-self-object-by-another-object-of-the-same-type-in-a-meth) – Matthias Dec 09 '19 at 12:05
  • @Matthias you've posted the same link as me(?) – brj Dec 09 '19 at 12:38
  • @brj My comment was created by Stackoverflow when I did a close vote with the duplicate. – Matthias Dec 09 '19 at 16:54

0 Answers0