python 魔法方法 __str__和__repr__

python

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

>>>

'''

以上是 python 魔法方法 __str__和__repr__ 的全部内容, 来源链接: utcz.com/z/389400.html

回到顶部