Yoo*_*rXD 7 python shell repr magic-methods
我知道在 Python Shell 中,当您键入时,>>> object它会显示该object.__repr__方法,如果您键入,>>> print(object)它也会显示该object.__str__方法。
但我的问题是,有没有一种__repr__在执行Python文件时进行打印的简短方法?
我的意思是,在 file.py 中,如果我使用print(object)它,它会显示object.__str__,如果我只是键入,object它不会显示任何内容。
我尝试过使用print(object.__repr__)但它打印<bound method object.__repr__ of reprReturnValue>
或者这是不可能的?
如果您只想打印表示形式而没有其他内容,那么
print(repr(object))
Run Code Online (Sandbox Code Playgroud)
将打印表示。您的调用出错的地方是缺少括号,如下所示:
print(object.__repr__())
Run Code Online (Sandbox Code Playgroud)
但是,如果您希望它成为更多信息的一部分并且您正在使用字符串格式,则不需要调用repr(),您可以使用转换标志!r
print('The representation of the object ({0!r}) for printing,'
' can be obtained without using "repr()"'.format(object))
Run Code Online (Sandbox Code Playgroud)