如何在Python中获取实例变量? [英] How to get instance variables in Python?

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

问题描述

Python中是否有内置方法来获取所有类的实例变量的数组?例如,如果我有以下代码:

Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code:

class hi:
  def __init__(self):
    self.ii = "foo"
    self.kk = "bar"

我有办法做到这一点吗?

Is there a way for me to do this:

>>> mystery_method(hi)
["ii", "kk"]

我本来是错误地要求类变量的.

I originally had asked for class variables erroneously.

推荐答案

每个对象都有一个__dict__变量,其中包含所有变量及其值.

Every object has a __dict__ variable containing all the variables and its values in it.

尝试

>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()

这篇关于如何在Python中获取实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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