如何使对象在打印功能触发时能够 return 其属性

How to make object able to return its properties when triggered by print function

在python中,如果我们打印一些对象,它会在打印函数触发时显示它们的属性。 例如:

print(int(69)) # 69

不像我自己定义的class是这样的:

class Foo:
  def __init__(self,oke):
    self.oke = oke

print(Foo('yeah')) # <__main__.Foo object at 0x000001EB00CDEEB0>

为什么 return 属性不正常?相反,它显示对象的内存地址?

我预计输出将是:

Foo(oke='yeah')

我知道我可以定义方法 getter get_oke(),但我想立即打印一个对象中的所有属性。

为您的 class 添加一个 __repr__ 方法。

From the docs

If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value

class Foo:
    def __init__(self,oke):
        self.oke = oke

    def __repr__(self):
        return f'Foo(oke="{self.oke}")'


print(Foo('yeah'))  # Foo(oke="yeah")