简体   繁体   中英

About Python dynamic instantiation

I am trying to figure out what's happening here. I want to keep a map (aka dict) of string keys and class values, in order to create new instances at runtime. I omitted the Farm class definition which is not important here.

Well, given the following code:

d = dict(farm = Farm)

# Dynamic instantiation with assignment
f1 = d["farm"]()
f2 = d["farm"]()

print(f1)
print(f2)

# Dynamic instantiation without assignment
print(d["farm"]())
print(d["farm"]())

I get the next output:

C:\Python3\python.exe E:/Programacion/Python/PythonGame/Prueba.py
<BuildingManager.Farm object at 0x00F7B330>
<BuildingManager.Farm object at 0x00F7B730>
<BuildingManager.Farm object at 0x00F7BAD0>
<BuildingManager.Farm object at 0x00F7BAD0>

 Process finished with exit code 0

Note that when I print them without being assigned, the ref is the same (0x00F7BAD0).

Why does instantiation in Python always return the same object?

Why does instantiation in Python always return the same object?

It doesn't. Look again at the IDs returned by your output:

Only the last one is recycled. And it's still not the same object.

So why are two those last IDs the same, but the first two are different?

In the first two cases you assign to a variable. That variable is kept around for the full execution of your program . Thus, each of the two object is unique, and remains unique.

Then, there is the third instantiation (the first print statement). This object is created, printed, but never assigned to any variable. Thus, after printing, Python can forget about it. And it does. In the last instantiation (second print statement), Python creates a new Farm instance, but assigns it the same ID as the one that is not kept around (number 3). That is just convenience, and under the hood, this is probably efficient as well (the memory space is available.) Thus, you see a recycled ID, even though it is in fact a new instance.

Python didn't return the same object, it returned a new object that just happened to be created to same address as the previous one. When print(d["farm"]()) is executed new object will be created and it's address is printed. Since there are no references to it it's available for garbage collection as soon as print returns. When second print(d["farm"]()) is executed it just happens to create the object to same address. Note that this won't happen when you assign the return value to a variable since object can't be garbage collected as long as there are references to it.

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