Search code examples
pythonlistconstructorappendmutable

Python updating list from constructor by object.attribute


If a class is created with the attributes: name and list and the name attribute has a default value and the list is appending the name. Is it possible in somehow when I create an object "a" and type "a.name = 'x' " that this 'x' will appear in the list given that the list is appending in the constructor?

class Person:
    list = []
    def __init__(self, name="Zed"):
        self.name = name
        self.list.append(name)

    def printList(self):
        print(self.list)


a = Person()
a.name = "Yasuo"
a.printList() #outputs Zed but Yasuo is expected.

Solution

  • You can make name a property, and implement a setter that updates the list.

    class Person:
        list = []
        def __init__(self, name="Zed"):
            self._name = name
            self.list.append(name)
        @property
        def name(self):
            return self._name
        @name.setter
        def name(self, name):
            if self._name in self.list:
                # remove the old name
                index = self.list.index(self.name)
                self.list[index] = name
            else:
                self.list.append(name)
            self._name = name
        def printList(self):
            print(self.list)
    
    a = Person()
    a.name = "Yasuo"
    a.printList() # prints ['Yasuo']