调用twi函数时,Python不会创建另一个对象

2024-04-19 23:31:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

所以在这个例子中。你知道吗

~/my\u软/my_程序.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\u soft/my\u模块/部署器.py

from  my_soft.my_module import Deployer

def my_function():

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

    return

~/my\u soft/my\u module/\uu init\uuuuuuuuuy.py

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

    def do_something(self):
        # method code

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

这是正常的行为吗?我错在哪里?你知道吗


Tags: 对象函数frompyimportobjectmydef
2条回答

马辛是对的。这些对象在出/入作用域时正在重新使用相同的内存位置。你知道吗

#!/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

Memory location is the same for both

除非您附加了一个C级调试器,否则我怀疑您是否有此信息。你知道吗

so they are the same object.

因为CPython和PyPy编写得很好,所以您希望它们以这种方式重用内存。事实上,我怀疑你看到了身份证的回收。你知道吗

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

相关问题 更多 >