是否可以在Python中运行实例变量

时间:2015-08-25 16:02:20

标签: python python-2.7

我们说我有这堂课:

class SomeClass()
    var1
    var2
    var3
.
.
.

有没有办法循环遍历所有这些实例变量,而无需通过名称调用每个变量(如果它是一个数组)?

4 个答案:

答案 0 :(得分:2)

查看inspect.getmembers(object[, predicate])

  

返回按名称排序的(名称,值)对列表中对象的所有成员。如果提供了可选的谓词参数,则仅包含谓词返回true值的成员。

>>> [name for name,thing in inspect.getmembers([])]
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__delslice__',    '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', 
'__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__','__reduce_ex__', 
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', 
'__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 
'insert', 'pop', 'remove', 'reverse', 'sort']
>>> 

答案 1 :(得分:1)

是的,有办法做到这一点。来自looping over all member variables of a class in python

class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False


members = [attr for attr in dir(Example()) if not callable(attr) and not attr.startswith("__")]
print members

会给你:

['blah', 'bool143', 'bool2', 'foo', 'foobar2000']

答案 2 :(得分:1)

是的,你可以这样做:

someobj = SomeClass()
for _attr in someobj.__dict__:
    # double underscore are mostly used by python
    if not _attr.startswith("__") and not callable(_attr):
        print someobj.__dict__[_attr]

答案 3 :(得分:1)

您可以使用inspect标准库模块。

请参阅Getting attributes of a class