python 魔法方法 __str__和__repr__

code1

class mytest():
    def __str__(self):
        return "hello" 
    def __repr__(self):
        return "world"

a=mytest()
print(a)
print(str(a))
print(repr(a))

outputs

hello
hello
world

code2

'''
Python 3.7.4 (v3.7.4:e09359112e, Jul  8 2019, 14:54:52) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> 
>>> 
>>> class mytest():
...     def __str__(self):
...             return "hello" 
...     def __repr__(self):
...             return "world"
... 
>>> 
>>> mytest()
world
>>> mytest()
world
>>> a=mytest()
>>> a
world
>>> print(a)
hello
>>> _
world
>>> 


'''

原文地址:https://www.cnblogs.com/sea-stream/p/13551499.html