0

I'm newbie in Python, so... I have this code:

def main():

    Obj1 = classA()
    Obj1.set_p1()
    Obj2 = classA()
    Obj1.del_p1()
    Obj3 = classA()
    classA.list.append(9)

    print(Obj1.list, Obj2.list, Obj3.list, classA.list)

class classA():

    list = []
    def set_p1(self):
        self.list.append(6)

    def del_p1(self):
        self.list = []

if __name__ == '__main__':
    main()

and I have this out: ([], [6, 9], [6, 9], [6, 9])

So I'cant get this: why Obj1.set_p1() change classA.list, but Obj1.del_p1() didn't do the same. Why classA.list.append(9) didn't do anything with Obj1.list?

Cœur
  • 37,241
  • 25
  • 195
  • 267
marxisthe
  • 3
  • 1

1 Answers1

0

Setting self.list to an empty list just creates a new instance attribute on Obj1 that hides the class attribute with the same name.

To clear the class-level list, you would need to access it via the class: self.__class__.list = [].

However, really both of these methods should be classmethods, since they don't access the instance at all.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895