gpt4 book ai didi

python - 如何在python中删除一个类

转载 作者:行者123 更新时间:2023-12-03 17:01:13 25 4
gpt4 key购买 nike

如果无法重新启动 python 进程,如何删除或更新类?例如像下面这样:

代码是:

# coding:utf8


class A(object):

value = 1


class B(A):

value = 1


subclasses = A.__subclasses__()
print(subclasses)
for subclass in subclasses:
print('{}:{}'.format(subclass, subclass.value))
print('')


class B(A):

value = 2


subclasses = A.__subclasses__()
print(subclasses)
for subclass in subclasses:
print('{}:{}'.format(subclass, subclass.value))
print('')


输出是:
[<class '__main__.B'>]
<class '__main__.B'>:1

[<class '__main__.B'>, <class '__main__.B'>]
<class '__main__.B'>:1
<class '__main__.B'>:2

如何删除第一个B类,让输出变为:
[<class '__main__.B'>]
<class '__main__.B'>:1

[<class '__main__.B'>]
<class '__main__.B'>:2

最佳答案

您可以使用 delgc删除子类然后垃圾收集:

class A(object):

def __init__(self):
a = 1

class B(A):

def __init__(self):
b = 1


subclasses = A.__subclasses__()
print(subclasses)


class B(A):

def __init__(self):
b = 2

del B
import gc
gc.collect()

subclasses = A.__subclasses__()
print(subclasses)

输出:
[<class '__main__.B'>]
[<class '__main__.B'>]

关于python - 如何在python中删除一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60447484/

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