在 Python 中打印函数时回显结果的正确术语

Correct terminology for result echoed when function printed in Python

我知道这可能在文档的某个地方,但反向搜索有点困难。当我们显式 print 一个函数(而不是调用它)时,回显结果的名称是什么?

例如。

def func():
    pass

print(func)

Returns:

<function func at 0x7f5f539587b8>

这个结果叫什么?另一个例子是 <class '__main__.a'>

特别感谢能告诉我这些结果是否也可以用于某些事情的好心人。

这是对象的"string representation"。这基本上是 Python 可以想出用字符串表示您的对象的最佳方式。

在第一种情况下,Python 告诉你,换句话说,"this is a function with name 'func' at memory location 0x7f5f539587b8"。这是它可以为您提供的最佳字符串表示,而无需您提供更好的表示。

在第二种情况下,Python 告诉你,“这是一个名为 'a' 的 class,它位于 'main ' 模块名称-space.

您可以通过定义 class 的 __repr__ 特殊方法来修改此值。 __repr__ 给出 "formal representation",__str__ 给出 "informal representation"。有关详细信息,请参阅 this

这个,例如:

class A:
    def __init__(self, unique_name):
        self.unique_name = unique_name

    def __repr__(self):
        return "object of type A and name %s in the name-space of %s" \
               % (self.unique_name, __name__)

a = A('foo')
print(a)

class B:
    pass

b = B()
print(b)

returns:

object of type A and name foo in the name-space of __main__
<__main__.B object at 0x7ffb9eb37668>