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

Time:08-03

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

CodePudding user response:

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
  • Related