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

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

    There are already a lot of answers in this thread but none of them particularly helped me, I had to work it out myself, so I hope this one is a little more informative.

    You just have to make sure you have parentheses at the end of your class, e.g:

    print(class())
    

    Here's an example of code from a project I was working on:

    class Element:
        def __init__(self, name, symbol, number):
            self.name = name
            self.symbol = symbol
            self.number = number
        def __str__(self):
            return "{}: {}\nAtomic Number: {}\n".format(self.name, self.symbol, self.number
    
    class Hydrogen(Element):
        def __init__(self):
            super().__init__(name = "Hydrogen", symbol = "H", number = "1")
    

    To print my Hydrogen class, I used the following:

    print(Hydrogen())
    

    Please note, this will not work without the parentheses at the end of Hydrogen. They are necessary.

    Hope this helps, let me know if you have anymore questions.

    0 讨论(0)
  • 2020-11-21 07:57

    As Chris Lutz mentioned, this is defined by the __repr__ method in your class.

    From the documentation of repr():

    For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

    Given the following class Test:

    class Test:
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
        def __repr__(self):
            return "<Test a:%s b:%s>" % (self.a, self.b)
    
        def __str__(self):
            return "From str method of Test: a is %s, b is %s" % (self.a, self.b)
    

    ..it will act the following way in the Python shell:

    >>> t = Test(123, 456)
    >>> t
    <Test a:123 b:456>
    >>> print repr(t)
    <Test a:123 b:456>
    >>> print(t)
    From str method of Test: a is 123, b is 456
    >>> print(str(t))
    From str method of Test: a is 123, b is 456
    

    If no __str__ method is defined, print(t) (or print(str(t))) will use the result of __repr__ instead

    If no __repr__ method is defined then the default is used, which is pretty much equivalent to..

    def __repr__(self):
        return "<%s instance at %s>" % (self.__class__.__name__, id(self))
    
    0 讨论(0)
  • 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.

    <class '__main__.Element'>
    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__)))
    
    0 讨论(0)
提交回复
热议问题