Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a class in python

Tags:

python

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
like image 533
qux Avatar asked Oct 27 '22 01:10

qux


People also ask

Can we delete class in Python?

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.

How do you delete a whole class in Python?

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.

What is __ del __ in Python?

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.

How do you delete in Python?

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.


1 Answers

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'>]
like image 110
Jamin Avatar answered Nov 15 '22 05:11

Jamin