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

前端 未结 9 1619
南方客
南方客 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:36

    A generic way that can be applied to any class without specific formatting could be done as follows:

    class Element:
        def __init__(self, name, symbol, number):
            self.name = name
            self.symbol = symbol
            self.number = number
    
        def __str__(self):
            return str(self.__class__) + ": " + str(self.__dict__)
    

    And then,

    elem = Element('my_name', 'some_symbol', 3)
    print(elem)
    

    produces

    __main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}
    

提交回复
热议问题