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

标签 python python-2.7

假设我有这门课:

class SomeClass()
    var1
    var2
    var3
.
.
.

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

最佳答案

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

Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument is supplied, only members for which the predicate returns a true value are included.

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

关于python - 是否可以在Python中运行实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32208791/

相关文章:

python - Lyapunov 指数代码输出 Nolds

python - 如何使用 python anytree 获取所有可能的分支

python - 破折号/阴谋在间隔= 500时歇斯底里

python 2.7在解析脚本时忽略sitecustomize.py中设置的默认编码

python - 删除 PyQt 中的小部件和布局

python - 阅读 RSS 提要并在 Django 模板中显示它 |提要解析器

Python Kerberos-1.1.1.tar.gz 在 Windows 上安装失败

mysql - Python django 外键 (1048, "Column ' USER_ID' cannot be null")

python - 如何在类属性定义中使用类方法

Python + BeautifulSoup : How to get wrapper out of HTML based on text?