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
>>> 


'''

 

 

 

 

 

 

posted @ 2020-08-23 23:55  anobscureretreat  阅读(125)  评论(0编辑  收藏  举报