0

I’m having trouble understanding what seems to be a basic OOP concept. Using the simple code below, I don’t understand why the append statement in one init method affects both class objects, while the addition to the test variable is class/object-specific. Why does the self.mylist.append(4) statement also add a 4 to the self.mylist in the other object?

mylist = [1,2,3]
test = 10

class first:
  def __init__(self, mylist, test):
    self.mylist = mylist
    self.test = test
    self.test+=100
    
class second:
  def __init__(self, mylist, test):
    self.mylist = mylist
    self.mylist.append(4)
    self.test = test
    self.test+=500
    
one = first(mylist, test)
two = second(mylist, test)

print(one.mylist)
print(two.mylist)

print(one.test)
print(two.test)

I expect the lists to be specific to the objects so that it would print 1,2,3 and 1,2,3,4 but both are 1,2,3,4.

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
OMATTID
  • 9
  • 1
  • 1
    When you pass `mylist` into the class constructors, it isn't making a copy, it's just passing a reference to the list. Therefore both objects are point to the same list. If you want to make a copy you can use `list(mylist)`. – Loocid Aug 11 '23 at 01:09
  • Thank you for the response. Why do both objects not point to the same “test” variable then if it’s essentially the same code? They print 110 and 510 separately. – OMATTID Aug 11 '23 at 01:16
  • Assigning or passing lists doesn't make a copy, it passes a reference to the list. – Barmar Aug 11 '23 at 01:32
  • The difference is that numbers are immutable. You're never modifying `self.test` in place, because you can't modify numbers. `self.mylilst.append(4)` modifies the list in place, it doesn't create a new list with the number appended. So all references to that list see the appended value. – Barmar Aug 11 '23 at 01:34
  • Ah ok so is that specific to lists? If so that solves my confusion because I was puzzled as to why it would alter the list everywhere in all classes with the same reference but simple variables changed within the init method or other methods stayed class-specific. Ty both very much – OMATTID Aug 11 '23 at 01:34
  • Thank you @Barmar, that actually makes sense and clears this up. Feel kinda dumb :) – OMATTID Aug 11 '23 at 01:35
  • It's not just lists, it's all modifiable types: lists, dictionaries, sets, many other classes. – Barmar Aug 11 '23 at 01:39
  • 1
    There's a difference between assigning a variable and calling a method on the variable. `x.append(3)` modifies the list in place. `x = x + [3]` creates a new list and assigns that to the variable. – Barmar Aug 11 '23 at 01:40
  • Makes complete sense - ty again – OMATTID Aug 11 '23 at 01:43
  • read this classic article by Stack Overflow legend: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Aug 11 '23 at 04:55

0 Answers0