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

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

    If you're in a situation like @Keith you could try:

    print(a.__dict__)
    

    It goes against what I would consider good style but if you're just trying to debug then it should do what you want.

    0 讨论(0)
  • 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}
    
    0 讨论(0)
  • 2020-11-21 07:36

    You need to use __repr__. This is a standard function like __init__. For example:

    class Foobar():
        """This will create Foobar type object."""
    
        def __init__(self):
            print "Foobar object is created."
    
        def __repr__(self):
            return "Type what do you want to see here."
    
    a = Foobar()
    
    print a
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-21 07:51
    >>> class Test:
    ...     def __repr__(self):
    ...         return "Test()"
    ...     def __str__(self):
    ...         return "member of Test"
    ... 
    >>> t = Test()
    >>> t
    Test()
    >>> print(t)
    member of Test
    

    The __str__ method is what happens when you print it, and the __repr__ method is what happens when you use the repr() function (or when you look at it with the interactive prompt). If this isn't the most Pythonic method, I apologize, because I'm still learning too - but it works.

    If no __str__ method is given, Python will print the result of __repr__ instead. If you define __str__ but not __repr__, Python will use what you see above as the __repr__, but still use __str__ for printing.

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

    Just to add my two cents to @dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:

    "[...] to return a string that would yield an object with the same value when passed to eval(), [...]"

    Given this class definition:

    class Test(object):
        def __init__(self, a, b):
            self._a = a
            self._b = b
    
        def __str__(self):
            return "An instance of class Test with state: a=%s b=%s" % (self._a, self._b)
    
        def __repr__(self):
            return 'Test("%s","%s")' % (self._a, self._b)
    

    Now, is easy to serialize instance of Test class:

    x = Test('hello', 'world')
    print 'Human readable: ', str(x)
    print 'Object representation: ', repr(x)
    print
    
    y = eval(repr(x))
    print 'Human readable: ', str(y)
    print 'Object representation: ', repr(y)
    print
    

    So, running last piece of code, we'll get:

    Human readable:  An instance of class Test with state: a=hello b=world
    Object representation:  Test("hello","world")
    
    Human readable:  An instance of class Test with state: a=hello b=world
    Object representation:  Test("hello","world")
    

    But, as I said in my last comment: more info is just here!

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