1

Imagine I need to populate one list with objects of some class and the set objects' fields. For example I can do it this way (not the best way, according to best practices, but for me more interesting is how it works behind the scene):

import random

class Point:
   coordinates = [0, 0]

ex = []
for i in range(0, 10):
    ex.append(Point())
    ex[i].coordinates[0] = random.randint(0, 25)
    ex[i].coordinates[1] = random.randint(0, 25)

for i in ex:
    print(i.coordinates)
    print(id(i.coordinates))

After this I end up with situation when all Points in ex list contains the same coordinates object (same id). But if I change assigning each list element to assigning list itself:

ex[i].coordinates = [random.randint(0, 25), random.randint(0, 25)]

It works as expected.

Could one point me out how it works under the hood and what's the difference between these 2 approaches?

IgorNikolaev
  • 1,053
  • 1
  • 12
  • 28
  • 3
    `coordinates` is a class variable, it's shared. – Dimitris Fasarakis Hilliard Apr 05 '17 at 10:24
  • Also see http://stackoverflow.com/questions/35520251/difference-between-class-attributes-instance-attributes-and-instance-methods-i – PM 2Ring Apr 05 '17 at 10:32
  • @JimFasarakisHilliard Did I get it right: I declared **exact** object (`[0,0]`) in the class declaration, so every `Point` instance will be with this **exact** object right after creation? And then, in my first case I just changed object (since list is mutable) and in second case I created brand new list? – IgorNikolaev Apr 05 '17 at 10:56
  • 1
    Close, in the first case you always mutate the same list reference `[0, 0]` in the second case you create an *instance variable* named `coordinates` which is completely independent from `coordinates` in the class. You need to remember that there's a class namespace and an instance namespace. Class namespaces are populated by names indented one level in the class body (or by assignment to the class). Instance namespaces by assigning to `self` or by assigning to the instance after it has been created. – Dimitris Fasarakis Hilliard Apr 05 '17 at 10:59

0 Answers0