0

I come from Java and I'm learning Python.

I want to work with a list of objects which contains a list of elements.

class O:
    o = []
    def add(self, i):
        self.o.append(i)

    def long(self):
        return len(self.o)

list = [ O(), O() ]    

Why calling 'add' at the first object is done also in the second?

>>> list[0].long()
0
>>> list[1].long()
0
>>> list[0].add(3)
>>> list[0].long()
1
>>> list[1].long()
1

What I'm doing wrong?

utrescu
  • 374
  • 2
  • 6
  • 1
    On a side note, your `long` method should be named `__len__` so that it works with the built-in function `len`, you shouldn't call your own list `list` as it shadows the built-in and if you're using Python 2.x `O` should inherit from `object`. – jonrsharpe Oct 08 '15 at 12:26
  • Nothing changes inheriting from object ... – utrescu Oct 08 '15 at 13:00
  • That's not true, although you might not see any immediate changes - research the difference between *"old-style"* and *"new-style"* classes. – jonrsharpe Oct 08 '15 at 13:01
  • Yes, there are 'internal' differences. But still 'add' is applied to both objects – utrescu Oct 08 '15 at 13:08
  • I never said it wouldn't be - the *duplicate* answers your question, my comment is just (as it explicitly states) a *side note*, raising some other issues with your code. – jonrsharpe Oct 08 '15 at 13:09

0 Answers0