0

I read a bit about getters and setters, but haven't quite figured it out. One of my issues is the declaration in the init method: how can I change only one attribute if the method needs to arguments? Any other methods are of course welcome as well.

class States:
    def __init__(self, f=0, n=0):
        self.state = n
        self.level_state = f

    @property
    def state(self, n):
        return self._state

    @state.setter
    def state(self, n):
        self._state = n

    @property
    def level_state(self, f):
        return self._level_state

    @level_state.setter
    def state(self, f):
        self._level_state = f

Example situation, changing the attributes individually:

Situation1:

States().state = 3

Situation2:

States().level_state = 2
Doe J
  • 145
  • 1
  • 1
  • 13
  • 1
    You are mixing the underscore-prefixed *private fields* with the non-underscore-prefixed *getter and setter methods*. Inside of all methods, use the fields. – Felk Mar 01 '18 at 14:36
  • 1
    Also don't assign values in the getters. Please read up on python properties – Felk Mar 01 '18 at 14:38
  • Your example makes no sense, because you modifying anonymous objects that are immediately eligible for garbage collection. `s = States(); s.state = 3`, but why wouldn't you just write `s = States(n=3)`? – chepner Mar 01 '18 at 14:45
  • Sorry for the awkward code, I fixed some glaring oversights. – Doe J Mar 01 '18 at 15:08
  • I'm still not sure how to modify two different attributes individually though – Doe J Mar 01 '18 at 15:10

1 Answers1

0

The code doesn't work because you've named the underlying attributes the same as the corresponding properties.

You need to use the same attribute names as the property getters/setters are referring to:

class States:
    def __init__(self, f=0, n=0):
        self._state = n          # <-- changed here
        self._level_state = f    # <-- changed here

    @property
    def state(self, n):
        return self._state

    @state.setter
    def state(self, n):
        self._state = n

    @property
    def level_state(self, f):
        return self._level_state

    @level_state.setter
    def state(self, f):
        self._level_state = f

But the simple solution for this case would be to not use properties at all:

class States:
    def __init__(self, f=0, n=0):
        self.state = n
        self.level_state = f
    # done
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Thank you for the answer, I ended up using two global variables which I would update, and it solved my issue. – Doe J Mar 01 '18 at 15:26