python - 如何使用函数显示对象的属性值

标签 python

我正在Python中创建一个类,该类对象具有各种属性。如何显示该对象的各种属性的值?

我发现使用 dir() 会返回对象的属性列表,但我想说的是

for attr in dir(object):
   print(f'{attr}: {self.attr}')

当然,这会导致错误,因为 self 没有名为 attr 的实际属性。

现在,我的函数如下所示:

def display_attrs(self):
    for attr in dir(self):
        print(f'{attr}: {self.attr}')

输出可能如下所示

len: 100
width: 50
height: 200

等等。我主要用它来调试。如果程序崩溃,我觉得查看对象的状态会很有帮助。

最佳答案

按照注释中的 Andrew Allen 的说法,在对象上使用 __dict__ dunder 函数,它将返回对象的字典表示形式,其中键是属性名称,值是属性的值。

关于python - 如何使用函数显示对象的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56838302/

相关文章:

python - 使用 Python 远程执行时 Curl 不打印

python - 为什么这段 Haskell 代码这么慢?

python - Pandas:将记录 reshape 为列

python - 在 C 中嵌入 Python - 段错误

python - 使用numpy后出现Opencv Otsu阈值错误?

python - 使用 Node.js AES CTR 加密并使用 PyCrypto 解密

python - 所有可能的因素对

python - ON DUPLICATE KEY UPDATE 导致运行时错误

python rtsp 转 webrtc

python - 合并单级 MultiIndex