If you cannot restart a python process, how can you delete or update a class? For example like below:
The code is:
# 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('')
The output is:
[<class '__main__.B'>]
<class '__main__.B'>:1
[<class '__main__.B'>, <class '__main__.B'>]
<class '__main__.B'>:1
<class '__main__.B'>:2
How can I delete the first B class, let the output change to:
[<class '__main__.B'>]
<class '__main__.B'>:1
[<class '__main__.B'>]
<class '__main__.B'>:2
You cannot force a Python object to be deleted; it will be deleted when nothing references it (or when it's in a cycle only referred to be the items in the cycle). You will have to tell your "Mastermind" to erase its reference.
Use the del keyword to delete class instance in Python. It's delete references to the instance, and once they are all gone, the object is reclaimed.
In Python, the __del__() method is referred to as a destructor method. It is called after an object's garbage collection occurs, which happens after all references to the item have been destroyed.
The del keyword in python is primarily used to delete objects in Python. Since everything in python represents an object in one way or another, The del keyword can also be used to delete a list, slice a list, delete a dictionaries, remove key-value pairs from a dictionary, delete variables, etc.
You can use del
and gc
to delete the subclass and then garbage collect:
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)
Output:
[<class '__main__.B'>]
[<class '__main__.B'>]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With