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

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

    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 "" % (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
    
    >>> print repr(t)
    
    >>> 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))
    

提交回复
热议问题