How to print instances of a class using print()?

前端 未结 9 1605
南方客
南方客 2020-11-21 07:27

I am learning the ropes in Python. When I try to print an object of class Foobar using the print() function, I ge

9条回答
  •  孤独总比滥情好
    2020-11-21 07:46

    For Python 3:

    If the specific format isn't important (e.g. for debugging) just inherit from the Printable class below. No need to write code for every object.

    Inspired by this answer

    class Printable:
        def __repr__(self):
            from pprint import pformat
            return "<" + type(self).__name__ + "> " + pformat(vars(self), indent=4, width=1)
    
    # Example Usage
    class MyClass(Printable):
        pass
    
    my_obj = MyClass()
    my_obj.msg = "Hello"
    my_obj.number = "46"
    print(my_obj)
    

提交回复
热议问题