__str__ and __repr__ methods

Python has a way to turn any value into a string: pass it to the repr() or str() function.

The function str() is used to convert the value into a form suitable for human reading, and repr() into a form readable by the interpreter.
The string obtained by the repr() function can usually be used to retrieve the object, and the input of repr() is friendly to python. Normally, the equation obj==eval(repr(obj)) holds true.

print('asd' == eval(repr('asd'))) # True and str() function does not have this function

>>>repr([0,1,2,3])
'[0,1,2,3]'
>>> repr('Hello')
"'Hello'"

>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285'
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class Person(object):
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender
    def __str__(self):
        return '(__str__: %s, %s)' % (self.name, self.gender)

    def __repr__(self):
        return '(__repr__: %r, %r)' % (self.name, self.gender)

p = Person('lh','male')
print(p)   # (__str__: lh, male)
print (p .__ str __ ()) # (__str__: lh, male)
print(p.__repr__())  # (__repr__: 'lh', 'male')

# %s => str(), more intelligent;
# %r => repr(), the processing is relatively simple and direct;
print("%s" %p)  # (__str__: lh, male)
print("%r" %p)  # (__repr__: 'lh', 'male')


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325570599&siteId=291194637