如何在 Python3 文件中打印 __repr__? (不在 shell 中)
How to print __repr__ in a Python3 file? (not in shell)
我知道在 Python Shell 中,当您键入 >>> object
时,它会显示 object.__repr__
方法,如果您键入 >>> print(object)
,它会显示 object.__str__
方法。
但我的问题是,有没有一种在执行 Python 文件时打印 __repr__
的捷径?
我的意思是,在 file.py 中,如果我使用 print(object)
,它会显示 object.__str__
,如果我只输入 object
,它什么也不会显示。
我试过使用 print(object.__repr__)
但它打印 <bound method object.__repr__ of reprReturnValue>
或者这是不可能的?
只需使用repr(object)
。
print(repr(object))
尝试:
print(some_object.__repr__())
__repr__
需要在打印之前调用,因为它是一种不同于 __file__
、__name__
等不需要调用的属性的方法(并且不能,就此而言)。 __str__()
方法也是如此:你需要用 - some_object.__str__()
调用它,而不是 some_object.__str__
.
我假设 OP 指的是带有单词 object
的一般对象,而不是名为 object
的实际 Python 对象,因此我使用了变量名 some_object
代替。正如评论中指出的那样,如果您确实执行 object.__repr__()
这将引发异常,因为必须在实例上调用 __repr__()
(即 object().__repr__()
将起作用)。
您可以使用旧的反引号
print(`object`)
在 Python 2 中,或
print(repr(object))
Python 2 和 3
如果您只想打印表示而不想其他,那么
print(repr(object))
将打印表示。您的调用出错的地方是缺少括号,因为以下内容也有效:
print(object.__repr__())
如果您希望它成为更多信息的一部分并且您正在使用字符串格式,则无需调用 repr()
,您可以使用转换标志 !r
print('The representation of the object ({0!r}) for printing,'
' can be obtained without using "repr()"'.format(object))
我知道在 Python Shell 中,当您键入 >>> object
时,它会显示 object.__repr__
方法,如果您键入 >>> print(object)
,它会显示 object.__str__
方法。
但我的问题是,有没有一种在执行 Python 文件时打印 __repr__
的捷径?
我的意思是,在 file.py 中,如果我使用 print(object)
,它会显示 object.__str__
,如果我只输入 object
,它什么也不会显示。
我试过使用 print(object.__repr__)
但它打印 <bound method object.__repr__ of reprReturnValue>
或者这是不可能的?
只需使用repr(object)
。
print(repr(object))
尝试:
print(some_object.__repr__())
__repr__
需要在打印之前调用,因为它是一种不同于 __file__
、__name__
等不需要调用的属性的方法(并且不能,就此而言)。 __str__()
方法也是如此:你需要用 - some_object.__str__()
调用它,而不是 some_object.__str__
.
我假设 OP 指的是带有单词 object
的一般对象,而不是名为 object
的实际 Python 对象,因此我使用了变量名 some_object
代替。正如评论中指出的那样,如果您确实执行 object.__repr__()
这将引发异常,因为必须在实例上调用 __repr__()
(即 object().__repr__()
将起作用)。
您可以使用旧的反引号
print(`object`)
在 Python 2 中,或
print(repr(object))
Python 2 和 3
如果您只想打印表示而不想其他,那么
print(repr(object))
将打印表示。您的调用出错的地方是缺少括号,因为以下内容也有效:
print(object.__repr__())
如果您希望它成为更多信息的一部分并且您正在使用字符串格式,则无需调用 repr()
,您可以使用转换标志 !r
print('The representation of the object ({0!r}) for printing,'
' can be obtained without using "repr()"'.format(object))