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

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

    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!

提交回复
热议问题