gpt4 book ai didi

python - 谁在引用 Joe?用于析构函数/清理的 Pythonic 方法?

转载 作者:行者123 更新时间:2023-12-05 08:36:59 25 4
gpt4 key购买 nike

我有以下 Python 代码:

#!/usr/bin/python3

import time

class Greeter:
def __init__(self, person):
self.person = person
print("Hello", person);

def __del__(self):
print("Goodbye", self.person);

def inspect(self):
print("I greet", self.person);

if __name__ == '__main__':
to_greet = []
try:
to_greet.append(Greeter("world"));
to_greet.append(Greeter("john"));
to_greet.append(Greeter("joe"));

while 1:
for f in to_greet:
f.inspect()
time.sleep(2)

except KeyboardInterrupt:
while (len(to_greet) > 0):
del to_greet[0]
del to_greet
print("I hope we said goodbye to everybody. This should be the last message.");

当我在 sleep 期间运行它并 Ctrl+C 时,我得到:

Hello world
Hello john
Hello joe
I greet world
I greet john
I greet joe
^CGoodbye world
Goodbye john
I hope we said goodbye to everybody. This should be the last message.
Goodbye joe

我不明白为什么 Goodbye joe 只在 This should be the last message 之后打印。谁在引用它?是 print 语句吗?即使我将 gc.collect() 放在最后一个 print 之前,我也看不到我们在最后一个 print 之前与 Joe 说再见。我该如何强制执行?

根据我一直在谷歌上搜索的内容,在这种情况下我似乎应该使用 with 语句,但是我不确定当要问候的人数是变量(例如,从 names.txt 文件中读取)或只是大。

看来我无法在 Python 中获得类似 C++ 的析构函数,那么实现这样的析构函数的最惯用和最优雅的方法是什么?我不一定需要删除/销毁对象,但我确实需要保证我们绝对向所有人说再见(有异常(exception),被信号杀死等)。理想情况下,我希望使用最优雅的代码来做到这一点。但就目前而言,抗异常应该没问题。

最佳答案

f。循环变量不在循环范围内;在 Python 中创建新范围的唯一语法结构是类、函数、理解和生成器表达式。

f 一直存在直到解释器关闭。虽然当前的 CPython 实现试图在解释器关闭时清理模块内容,但我认为这在任何地方都没有得到保证。

关于python - 谁在引用 Joe?用于析构函数/清理的 Pythonic 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67082892/

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