简体   繁体   中英

How does python manage variables inside a class?

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?

The reason is Small Integer Caching. Python caches small integers, which are integers between -5 and 256. These numbers are used so frequently that it's better for performance to already have these objects available. So these integers will be assigned at startup. Then, each time you refer to one, you'll be referring to an object that already exists. This is the reason, you see the same reference for variables with value 0 .

However, this is true to CPython, I have read it has some differences based on the other implementations. Refer this answer for a broader explanation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM