My machine learning course 「 Meituan 」 Algorithmic Engineer takes you to machine learning It's starting to update , You are welcome to subscribe ~
Any algorithm 、 Programming 、AI Questions about industry knowledge or blog content , You can scan the official account at any time. 「 Turing's cat 」, Join in ” Study Group “, Sand sculpture blogger online Q & A ~ Besides , There are more in the official account. AI、 Algorithm 、 Programming and big data knowledge sharing , And free nodes and learning materials . Other platforms ( You know /B standing ) It's the same name 「 Turing's cat 」, Don't get lost ~
__repr__ and __str__ Both methods are used for display ,__str__ It's user oriented , and __repr__ For programmers .
The printing operation will first try __str__ and str Built in functions (print The internal equivalent form of operation ), It should usually return a friendly display .__repr__ For all other environments : It is used for prompt response in interactive mode and repr function , If not used __str__, Will use print and str. It should usually return an encoded string , Can be used to recreate objects , Or give developers a detailed display .
When we want to have a unified display in all environments , Can be refactored __repr__ Method ; When we want to support different displays in different environments , For example, the end-user display uses __str__, Programmers use the underlying... During development __repr__ To display , actually __str__ It's just covered __repr__ For a more user-friendly display .
Here's an example :
class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
def __str__(self):
return '(Person: %s, %s)' % (self.name, self.gender)
Now? , Interactive command line with print try :
>>> p = Person('Bob', 'male')
>>> print p
(Person: Bob, male)
however , If you knock a variable directly p:
>>> p
<main.Person object at 0x10c941890>
Seems to be __str__() Will not be called .
because Python Defined __str__() and __repr__() The two methods ,__str__() Used to display to the user , and __repr__() Used to display to developers .
There is a definition of laziness __repr__ Methods :
class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
def __str__(self):
return '(Person: %s, %s)' % (self.name, self.gender)
__repr__ = __str__