如何在 Python 中枚举对象的属性? [英] How to enumerate an object's properties in Python?

查看:43
本文介绍了如何在 Python 中枚举对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# 中通过反射来实现.在 Javascript 中,它很简单:

I C# we do it through reflection. In Javascript it is simple as:

for(var propertyName in objectName)
    var currentPropertyValue = objectName[propertyName];

如何用 Python 实现?

How to do it in Python?

推荐答案

for property, value in vars(theObject).items():
    print(property, ":", value)

请注意,在极少数情况下,会有 __slots__ 属性,此类类通常没有 __dict__.

Be aware that in some rare cases there's a __slots__ property, such classes often have no __dict__.

这篇关于如何在 Python 中枚举对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆