我知道在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))
将打印表示。调用错误的地方是缺少的括号,因为下面的方法也适用:
print(object.__repr__())
但是,如果您希望它成为更多信息的一部分,并且您正在使用字符串格式,则无需调用repr()
,可以使用conversion标志!r
print('The representation of the object ({0!r}) for printing,'
' can be obtained without using "repr()"'.format(object))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句