How to define a __str__ method for a class?

Actually the same mechanism as for object instances applies for types. Types are just objects themselves, so they are converted to strings by calling the __str__() method on their type, which is called the “metaclass”. So you have to overwrite the __str__() method on the metaclass:

class fancytype(type):
    def __str__(self):
        return self.__name__
class ham(object):
    __metaclass__ = fancytype
print ham

prints

ham

Leave a Comment