gpt4 book ai didi

Python 'with' 不删除对象

转载 作者:太空狗 更新时间:2023-10-29 20:34:20 26 4
gpt4 key购买 nike

尝试正确删除 Python 对象。我正在创建一个对象,然后假设用“with”语句删除它。但是当我在“with”语句关闭后打印出来时......对象仍然存在:

class Things(object):
def __init__(self, clothes, food, money):
self.clothes = clothes
self.food = food
self.money = money

def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
print('object deleted')

with Things('socks','food',12) as stuff:
greg = stuff.clothes
print(greg)


print(stuff.clothes)

返回:

socks
object deleted
socks

最佳答案

Python 的with 语句与删除对象无关——它与资源管理有关。 __enter____exit__ 方法是为您提供资源初始化和销毁​​代码,即您可以选择在那里删除一些东西,但没有隐式删除对象。阅读此 with article更好地了解如何使用它。

对象在 with 语句之后保留在范围内。如果需要,您可以对其调用 del。由于它在范围内,您可以在它的基础资源关闭后查询它。考虑这个伪代码:

class DatabaseConnection(object):
def __init__(self, connection):
self.connection = connection
self.error = None

def __enter__(self):
self.connection.connect()

def __exit__(self, exc_type, exc_val, exc_tb):
self.connection.disconnect()

def execute(self, query):
try
self.connection.execute(query)
except e:
self.error = e

with DatabaseConnection(connection) as db:
db.execute('SELECT * FROM DB')
if db.error:
print(db.error)

del db

我们不想让数据库连接保持比我们需要的时间更长的时间(另一个线程/客户端可能需要它),所以我们允许释放资源(隐式地在 的末尾 block),但是之后我们可以继续查询对象。然后我添加了一个显式的 del 来告诉运行时代码已完成变量。

关于Python 'with' 不删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36002705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com