2015-01-16 43 views
0

我在Python中的函数中创建一个对象。当函数结束时,所有对象的引用都应该被删除(只有一个实例),以及对象本身。当函数被调用两次时,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。当函数返回时,该对象应该被删除。当我第二次输入选项'something'时,python再次调用my_function,同时它应该初始化另一个对象Deployer。 (即再次调用my_function时,它不会创建另一个对象,但它会像以前一样使用它)。两者的内存位置相同,因此它们是同一个对象。

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

回答

3

存储位置是两个

除非你是一个连接C级调试器一样,我怀疑你有这个信息。

因此它们是同一个对象。

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

编辑:还请注意,这种方式的回收ids是完全安全的。任何时候都不会有两个物体拥有相同的ID。唯一的出路就是程序存储ID。没有理由这样做。

+1

@ Atem18尝试引进一些变化到第一对象,但不是第二个,看是肯定的,如果他们真的一样。 –

+0

@ivan_pozdeev这是不可能的;测试永远不会在函数调用中保留该对象。这就是为什么这种ID的回收发生。 – Marcin

2

Marcin是对的。对象重复使用相同的内存位置,因为它们会在/在范围内。

#!/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 
相关问题