0
  • strangest python behavior I have seen, if the member of a class is a dict, then changing the dict value of one instance, changes the dict value of all instances, this doesn't happen for non-dict members
class Apple:
    prop = { 'color': 'red' }
    color2 = 'red'

a1 = Apple()
a2 = Apple()

a1.prop['color'] = 'blue'
a1.color2 = 'blue'

print(a1.prop, a1.color2)
print(a2.prop, a2.color2)

  • output:
{'color': 'blue'} blue
{'color': 'blue'} red
  • 4
    You are modifying a class variable and not a state variable – fibonachoceres Dec 20 '21 at 14:22
  • `prop` and `color2` belonged to `Apple`, not its instances. Instances just borrow their class's attributes if they don't have it. So when you *modified* `color2`'s `dict` by indexing and assigning one of its elements, it's the class that changes. However, when you did `a1.color2 = 'blue'`, you gave the *instance* its own `color2` so it won't use the class's. Check `Apple.color2` and `a2.color2`, they will still be `'red'`. Mutability doesn't matter here, `a1.color2 = ['blue', 'moon']` would have the same effect. – BatWannaBe Dec 20 '21 at 14:31

1 Answers1

0

You are modifying a class/static variable and not a state variable. Class variables are shared across all instances of the same class. Instance variables need to set to the self property.

As stated by @BatWannaBe and @WonderCricket, When you modified the string class variable, you removed that instance's reference to the original class property. Modifying the dictionary required accessing the property and modifying its internal state, but the root reference to the same dictionary was not changed.

class Apple:
  def __init__(self):
    self.prop = { 'color': 'red' }   
    self.color2 = 'red'


a1 = Apple()
a2 = Apple()

a1.prop['color'] = 'blue'
a1.color2 = 'blue'

print(a1.prop, a1.color2)
print(a2.prop, a2.color2)

fibonachoceres
  • 727
  • 4
  • 14
  • 1
    It might be good to note why this only applies to `dict` and not `str`. Strings are immutable and dictionaries are mutable – Wondercricket Dec 20 '21 at 14:25
  • Yes you're right, thanks for adding that. I believe that was the main source of confusion that led to the question being asked. – fibonachoceres Dec 20 '21 at 14:27