1

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.

1 Answer 1

1

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']
Sign up to request clarification or add additional context in comments.

19 Comments

I agree with you but I dont know why they want us to do it the append under the __init__(), I think that is stupid. And they also want the "Zed" to be overwritten when we do "a.name" so that in this case a.printList() prints Yasuo without Zed in the list.
I tried to put the list on the body under the class, but it still did not work... Does it have to do with that the list is a default mutable attribute in this case and that it should be implemented in different way? I think it is very confusing...
Why is it a list if they want to replace instead of append?
I've changed the answer to replace self.list[0] with the new name.
Are you sure list is supposed to be an instance attribute rather than a class attribute? Maybe they want a list of all the instances, or a list of the names of all the people?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.