Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change Class Name

Is there a way to change the name of a class (not just the class objects, but the class itself)?

For example:

class Foo:
    # stuff


obj1 = Foo()
# Code that renames Foo class to Food
obj2 = Food()

if obj1 == obj2:
    print("The class has been renamed!")

If the code works, obj1 and obj2 should be the same. Is this even possible to do in python? If so, how do I do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Assign the new name from the old name so you can call the new name. Use del oldname to prevent caling the old name. And change the __name__ and __qualname__ attributes of the class so that the new name will appear in type descriptors.

Food = Foo
del Foo
Food.__name__ == Food.__qualname__ = "Food"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading