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

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

    A prettier version of response by @user394430

    class Element:
        def __init__(self, name, symbol, number):
            self.name = name
            self.symbol = symbol
            self.number = number
    
        def __str__(self):
            return  str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))
    
    elem = Element('my_name', 'some_symbol', 3)
    print(elem)
    

    Produces visually nice list of the names and values.

    
    name = my_name
    symbol = some_symbol
    number = 3
    

    An even fancier version (thanks Ruud) sorts the items:

    def __str__(self):
        return  str(self.__class__) + '\n' + '\n'.join((str(item) + ' = ' + str(self.__dict__[item]) for item in sorted(self.__dict__)))
    

提交回复
热议问题