0

I have two classes as below:

class foo:
        def __init__(self):
            self.val = 10

class foo2:
    def __init__(self):
        self.val = 1000

When I copy an instance of class foo into a variable and then change a value of class foo, the variables changes. This is because the foo is a reference type and every change in foo changes its instances as well.

    f = foo()
    b = f 
    print(b.val)
    f.val = 20
    print(b.val)
    >> 10
    >> 20

But if I copy the class foo2 into class foo, the variable b does not change to 1000. What is the explanation for this?

f = foo2()
print(f.val)
print(b.val)

>> 1000
>> 20
Amir Jalilifard
  • 2,027
  • 5
  • 26
  • 38
  • 1
    You haven't copied anything, you've assigned `f` to a new instance of a different class – Sayse Oct 17 '19 at 19:35
  • 1
    https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/ – gstukelj Oct 17 '19 at 19:36
  • 2
    You didn't "copy the class foo2 into the class foo"; you made `f` point to an entirely different object. That doesn't affect the object previously referenced by `f` (and still referenced by `b`). – chepner Oct 17 '19 at 19:37
  • but b points to f and f points to foo. Now, if f points to foo2, be should point to foo2 as well. What am I missing here? – Amir Jalilifard Oct 17 '19 at 19:40
  • 1
    Why should `b` point to the instance of `foo2`? `b` doesn't point to `f`; `b` and `f` pointed to the same object. You just changed what `f` points to. Read https://nedbatchelder.com/text/names.html. – chepner Oct 17 '19 at 19:41
  • Python doesn't have a distinction between reference types and primitives, everything acts like a reference type. You would just say "object" – juanpa.arrivillaga Oct 17 '19 at 19:43
  • "b points to f" no, it doesn't. `b` and `f` happened to refer to the same object. Then you changed what `f` is referencing, but that doesn't affect `b` – juanpa.arrivillaga Oct 17 '19 at 19:56

1 Answers1

0

It's this line:

b = f

You haven't created a copy of the f object, you've created two different references to the same f object. A change to either one will change both, because they're the same object.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622