Python 当函数被调用两次时不创建另一个对象

Python does not create another object when a function is called twice

我在 Python 的函数中创建了一个对象。当函数结束时,应该删除对该对象的所有引用(只有一个实例),以及对象本身。

所以在这个例子中。

~/my_soft/my_program.py

from my_soft.my_module import deployers as D

def main():
    while True:
        ## ask and wait for user option
        if opt == 'something':
            D.my_function()

~/my_soft/my_module/deployers.py

from  my_soft.my_module import Deployer

def my_function():

    dep = Deployer(param1, param2)
    dep.do_something()

    return

~/my_soft/my_module/__init__.py

class Deployer(object):
    def __init__(self, param1, param2):
        ## initialise my attributes

    def do_something(self):
        # method code

现在,当我执行程序并第一次选择选项 'something' 时,它会调用 my_function 并在变量 dep 中创建对象 Deployer。当函数returns时,对象应该被删除。当我第二次输入时,选项 'something'、python 再次调用 my_function,同时它应该初始化另一个对象 Deployer。 (即再次调用时 my_function 它不会创建另一个对象,但它使用与以前相同的对象)两者的内存位置相同,因此它们是相同的对象。

这是正常行为吗?我哪里错了?

Memory location is the same for both

除非你附加了一个 C 级调试器,否则我怀疑你有这个信息。

so they are the same object.

因为 CPython 和 PyPy 写得很好,你会期望它们以这种方式重用内存。事实上,我怀疑您看到了 ID 的回收。

编辑:另请注意,以这种方式回收 ID 是完全安全的。任何时候都不会有两个对象具有相同的 ID。唯一可能出错的方法是程序存储 id。没有理由这样做。

Marcin 是对的。这些对象在进入 out/in 范围时重新使用相同的内存位置。

#!/usr/bin/env python

import datetime

def main():
    while True:
        input()
        my_function()

def my_function():
    dep = Deployer()
    print(hex(id(dep)))
    dep.do_something()

class Deployer:
    def __init__(self):
        try:
            print(self.time)
        except AttributeError as ex:
            print(ex)

        self.time = datetime.datetime.now()

    def do_something(self):
        print(self.time)

if __name__ == "__main__":
    main()

输出:

'Deployer' object has no attribute 'time'
0x7f2072d79f60
2015-01-16 05:47:51.561046

'Deployer' object has no attribute 'time'
0x7f2072d79f60
2015-01-16 05:47:51.926064

'Deployer' object has no attribute 'time'
0x7f2072d79f60
2015-01-16 05:47:52.241109

'Deployer' object has no attribute 'time'
0x7f2072d79f60
2015-01-16 05:47:52.547327

'Deployer' object has no attribute 'time'
0x7f2072d79f60
2015-01-16 05:47:52.892630