Home > Back-end >  Change Class Name
Change Class Name

Time:01-11

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?

CodePudding user response:

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"

CodePudding user response:

You can copy the class and delete the original:

class Foo:
    def test(self):
        pass


obj1 = Foo()

# Copy and delete original
Food = Foo
del Foo

obj2 = Food()

However if obj1 == obj2 will not work because if references the class instance not the class itself.

  •  Tags:  
  • Related