In fact: __str__ and __repr__ the same effect, people say: __str__ is user-oriented, and __repr__ is for programmers, boom you?
Website Explanation:
-
object.
__repr__
( self )?
Called by therepr()
Built-in function and by string conversions (reversequotes) to compute the "official" string representation of an object. If at allpossible, this should look like a valid Python expression that could is used torecreate an object with the same Value (given an appropriate environment).Ifthis is not possible, A string of the form <...some useful description...>
should be returned . The return value must be a String Object. If a classdefines__repr__()
but not__str__()
, Then__repr__()
Is alsoused when a "informal" string representation of instances of that class isrequired.
-
object.
__str__
( self )?
Called by thestr()
Built-in function and by theprint
Statement to compute the "informal" string representation of an object.Thisdiffers from__repr__
()
In that itDoes not has to be a valid pythonexpression: A more convenient or concise representation could be used instead. The return value must is a string object.
Read the explanation, where to say is the user-oriented, and where the programmer???? See the bold word No, see the slide line has not??? It's all about acting for everyone!!! If you want to be in your own position, well, it seems like such a thing, it is really obscene and vague expression.
Do not say, first small try:
#!/usr/bin/python
#-*-Coding:utf-8-*-
Class Student (object):
def __init__ (self, name):
Self.hah = Name
Class Str (Student):
def __str__ (self):
Return ' STR (name:%s) '%self.hah
Class Repr (Student):
def __repr__ (self):
Return ' repr (name:%s) '% Self.hah
s = Student (' Michael ')
Print S.hah
Print Str (' You ')
Print repr (' Me ')
Recently very crazy, no, not recently, but at this stage of me, very much like godless, if I do not express, it is really sorry ... You are right, you also come to godless me ah, come ah, mutual hurt Ah!!!
Python Class: Object-oriented advanced programming __str__/__REPR__