How to append a list in Python if it has been decorated in a class?

Question:

So the code below uses decorators for the variable _states. I want to append the list inside my class, so I wrote the method state_my_append. But the problem is it isn’t working.

On the other hand, if I call my variable outside of my class, it runs just fine. I have placed the outputs of the print statements as comments.

class State():
    def __init__(self):
        self._states = []

    @property
    def state(self):
        return self._states
    @state.setter
    def state(self, val):
        self._states = val

    def state_my_append(self, val):
        self._states.append(val)

    def __getitem__(self, idx):
        return self._states[idx]

    def __setitem__(self, idx, value):
        self._states[idx] = value

    def __repr__(self):
        return " -> ".join(str(state) for state in reversed(self.states))


s = State()

s.states = [1, 2, 3]
print(s) # 3 -> 2 -> 1

s.state_my_append(5)
print(s) # 3 -> 2 -> 1

s.states.append(5)
print(s) # 5 -> 3 -> 2 -> 1
Asked By: Al-Baraa El-Hag

||

Answers:

Slight edits make it work:

class State():
    def __init__(self):
        self._states = []

    @property
    def states(self):
        return self._states
    @states.setter
    def states(self, val):
        self._states = val

    def states_my_append(self, value):
        self._states.append(value)

    def __getitem__(self, idx):
        return self._states[idx]

    def __setitem__(self, idx, value):
        self._states[idx] = value

    def __repr__(self):
        return " -> ".join(str(state) for state in reversed(self.states))


s = State()

s.states = [1, 2, 3]
print(s) # 3 -> 2 -> 1

s.states_my_append(5)
print(s) # 3 -> 2 -> 1

s.states.append(5)
print(s) # 5 -> 3 -> 2 -> 1

3 -> 2 -> 1
5 -> 3 -> 2 -> 1
5 -> 5 -> 3 -> 2 -> 1
Answered By: Matt
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.