Magic method - simple customization (\\\\\\\\\\\\\\\\\\\

Posted by wing_zero on Tue, 05 May 2020 08:20:42 +0200

Reading notes:
Both repr and str are used for display. str is user oriented, while repr is programmer oriented.
repr means representation and description.
To display objects using print(Object), you need to refactor str. To directly input class objects for printing, you need to refactor the repr.
In python, str is usually in this format.

class A:
    def __str__(self):
    return "this is in str"

In fact, STR is called by the print function, which is usually return. This thing should be in the form of a string. If you don't want to convert with the str() function. When you print a class, the first thing print calls is the str defined in the class, such as:

class strtest:  
    def __init__(self):  
        print ("init: this is only test" )
    def __str__(self):  
        return "str: this is only test"  

if __name__ == "__main__":  
    st=strtest()  
    print (st)  
init: this is only test
str: this is only test

Give me another corn!

>>> class Test():
    def __init__(self):
        self.prompt = "hello,zss041962"

>>> t = Test()
>>> t
<__main__.Test object at 0x0000000002F3EF28>
>>> print(t)
<__main__.Test object at 0x0000000002F3EF28>

# See? The above printing class object is not very friendly. It shows the memory address of the object
# Let's refactor the "repr" and "str" of this class to see the difference between them

>>> #Refactor__
>>> class TestRepr(Test):
    def __repr__(self):
        return "Show:%s"%self.prompt
# After refactoring the repr method, both the direct output object and the print ed information are displayed in the format defined in our repr method
>>> t1 = TestRepr()
>>> t1
Show:hello,zss041962
>>> print(t1)
Show:hello,zss041962


>>> #Refactoring__
>>> class TestStr(Test):
    def __str__(self):
        return "Show:  %s"%self.prompt
# You will find that when you output the object ts directly, it does not follow the format defined in our str method, but the information output with print changes
>>> t2 = TestStr()
>>> t2
<__main__.TestStr object at 0x00000000031C33C8>
>>> print(t2)
Show:  hello,zss041962












Topics: Python