How to define a __str__ method for a class?

后端 未结 3 1295
南旧
南旧 2020-12-01 15:55

In Python, the object class serves as the root superclass for all the (new-style) classes. By default at least, applying str and repr

相关标签:
3条回答
  • 2020-12-01 16:12

    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
    
    0 讨论(0)
  • 2020-12-01 16:31

    You can also set the default metaclass for a whole module like this

    class fancytype(type):
        def __str__(self):
            return self.__name__
    
    __metaclass__ = fancytype
    
    class ham:
        pass
    print ham
    
    0 讨论(0)
  • 2020-12-01 16:33

    Here's the new answer for Python 3. Basically, you pass in a metaclass as a keyword parameter to the class definition.

    class fancytype(type):
        def __str__(self):
            return self.__name__
    class ham(metaclass=fancytype):
        pass
    print(ham)
    

    prints

    ham
    
    0 讨论(0)
提交回复
热议问题