Search code examples
pythonpython-3.xclassgetter-setter

How do change class attributes individually?


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

Solution

  • 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