Let's say I have the following two python files.
foo.py
class Foo:
    def __init__(self):
        self.my_var = 0
    
    def print_var(self):
        print(f"self.my_var: {self.my_var}")
        print(f"self.my_var address: {hex(id(self.my_var))}")
    def set_var(self, v):
        self.my_var = v
test_foo.py
import foo
f1 = foo.Foo()
f2 = foo.Foo()
print(f"\n=========== first print ===========")
f1.print_var()
f2.print_var()
f1.set_var(3)
print(f"\n=========== second print ===========")
f1.print_var()
f2.print_var()
When I run python3 test_foo.py, I get the following result:
=========== first print ===========
self.my_var: 0
self.my_var address: 0x7ffb7477a180   # Why do f1's and f2's `self.my_var` refer to the same instance?
self.my_var: 0
self.my_var address: 0x7ffb7477a180
=========== second print ===========
self.my_var: 3
self.my_var address: 0x7ffb7477a1e0
self.my_var: 0
self.my_var address: 0x7ffb7477a180
I'm curious about why in the first print, f1's and f2's self.my_var refer to the same instance.
I mean they all refer to the vairable located at 0x7ffb7477a180.
I expected they would refer to different instances.
Here's my expected output, though I know it's wrong.
=========== first print ===========
self.my_var: 0
self.my_var address: 0x7ffb7477a1e0
self.my_var: 0
self.my_var address: 0x7ffb7477a180
=========== second print ===========
self.my_var: 3
self.my_var address: 0x7ffb7477a1e0
self.my_var: 0
self.my_var address: 0x7ffb7477a180
Does python have any document explaining how it manages variables inside a class?
 
    