【问题标题】:Is it possible to run through instance variables in Python [duplicate]是否可以在 Python 中运行实例变量 [重复]
【发布时间】:2015-08-25 16:02:19
【问题描述】:

假设我有这个课程:

class SomeClass()
    var1
    var2
    var3
.
.
.

有没有一种方法可以循环遍历所有这些实例变量,而无需通过名称调用每个变量(就像它是一个数组一样)?

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

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

    在按名称排序的 (name, value) 对列表中返回对象的所有成员。如果提供了可选的谓词参数,则只包括谓词返回真值的成员。

    >>> [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']
    >>> 
    

    【讨论】:

      【解决方案2】:

      是的,你可以这样做:

      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】:

      是的,有办法做到这一点。来自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']
      

      【讨论】:

        【解决方案4】:

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

        Getting attributes of a class

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-08-14
          • 2018-09-11
          • 1970-01-01
          • 2021-12-29
          • 2019-09-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多