0

Why is it that the object b has the same variables as a and not unique ones?

class FOO: 
 
    def __init__(self):
         FOO.x = [3, 1]
         self.y = [9, 4] 
 
    def g(self):
         FOO.x[1] = FOO.x[1] + 7
         self.y *= 2
         return FOO.x + self.y 
 
a, b = FOO(), FOO() 
print(a.g()) 
print(a.g()) 
print(b.g())

Why do I get this output:

[3, 8, 9, 4, 9, 4]

[3, 15, 9, 4, 9, 4, 9, 4, 9, 4]

[3, 22, 9, 4, 9, 4]

and not this?

[3, 8, 9, 4, 9, 4]

[3, 15, 9, 4, 9, 4, 9, 4, 9, 4]

[3, 8, 9, 4, 9, 4]

Isn't each object unique?

Community
  • 1
  • 1
  • 5
    Why are you using `FOO.x` instead of `self.x`? – Patrick Haugh Jun 21 '19 at 18:46
  • 2
    Do you know the difference between `Foo.x` and `self.x`? Why did you use `Foo.x` and `self.y`? – CristiFati Jun 21 '19 at 18:46
  • 2
    Because you are changing class attributes `Foo.x` which changes it for all instances , instead use `self.x` which is an instance attribute – Devesh Kumar Singh Jun 21 '19 at 18:47
  • oh, I didn't notice that. btw, that's a question that I was trying to solve but didn't notice the Foo.x instead of self still why does b inherit from a – Mahmood Jazmawy Jun 21 '19 at 18:48
  • @JoelBerkeley , my question is why does b inherit from a – Mahmood Jazmawy Jun 21 '19 at 18:49
  • 2
    Yes, which boils down to the difference between class and instance variables (btw `b` doesn't _inherit_ from `a` - _inherit_ means sth else) – joel Jun 21 '19 at 18:50
  • 1
    @JoelBerkeley, I feel stupid how I didn't notice that, thanks anyway. I didn't notice that the variable is a class variable. I thought that b inherited something from a since I didn't notice the Foo.x – Mahmood Jazmawy Jun 21 '19 at 18:51
  • @JoelBerkeley, sorry if I used wrong terms since I don't study in english – Mahmood Jazmawy Jun 21 '19 at 18:53
  • 1
    ah no bother. we all miss things. and I picked up on _inherit_ because it means sth very specific in programming and you or someone else will get confused if you try to use it to mean something else – joel Jun 21 '19 at 18:56

1 Answers1

0

The FOO.x variable belongs to the FOO class, not to each instance. So, when you're adding 7 to FOO[1], you're changing the value for all object instances.

Alain T.
  • 40,517
  • 4
  • 31
  • 51