python - 遍历python中的对象属性

我有一个带有多个属性和方法的 python 对象。我想迭代对象属性。

class my_python_obj(object):
    attr1='a'
    attr2='b'
    attr3='c'

    def method1(self, etc, etc):
        #Statements

我想生成一个包含所有对象属性及其当前值的字典,但我想以动态方式进行(所以如果以后我添加另一个属性,我不必记得将我的函数更新为好)。

在 php 中的变量可以用作键,但在 python 中的对象是 Not Acceptable ,如果我为此使用点表示法,它会创建一个带有我的 var 名称的新属性,这不是我的意图。

只是为了让事情更清楚:

def to_dict(self):
    '''this is what I already have'''
    d={}
    d["attr1"]= self.attr1
    d["attr2"]= self.attr2
    d["attr3"]= self.attr3
    return d

·

def to_dict(self):
    '''this is what I want to do'''
    d={}
    for v in my_python_obj.attributes:
        d[v] = self.v
    return d

更新: 属性是指这个对象的变量,而不是方法。

最佳答案

假设你有一个类如

>>> class Cls(object):
...     foo = 1
...     bar = 'hello'
...     def func(self):
...         return 'call me'
...
>>> obj = Cls()

在对象上调用 dir 会返回该对象的所有属性,包括 python 特殊属性。虽然有些对象属性是可调用的,比如方法。

>>> dir(obj)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo', 'func']

您始终可以使用列表推导过滤掉特殊方法。

>>> [a for a in dir(obj) if not a.startswith('__')]
['bar', 'foo', 'func']

或者如果您更喜欢 map /过滤器。

>>> filter(lambda a: not a.startswith('__'), dir(obj))
['bar', 'foo', 'func']

如果要过滤掉方法,可以使用内置的callable作为检查。

>>> [a for a in dir(obj) if not a.startswith('__') and not callable(getattr(obj, a))]
['bar', 'foo']

您还可以使用检查您的类与其实例对象之间的差异。

>>> set(dir(Cls)) - set(dir(object))
set(['__module__', 'bar', 'func', '__dict__', 'foo', '__weakref__'])

https://stackoverflow.com/questions/11637293/

相关文章:

c++ - 如何在 Linux 上执行适用于 x86、arm、GCC 和 icc 的原子操作?

python - 在 matplotlib 中设置颜色条范围

python - Numpy:从二维数组中获取随机行集

linux - 如何在复杂的文本文件中替换 shell 变量

linux - 我应该使用什么 Linux shell?

python - 如何列出导入的模块?

python - 通过比较两个绝对路径获取相对路径

c++ - 如何调用存储在char数组中的机器码?

linux - 为什么 docker 有能力运行不同的 linux 发行版?

linux - 从命令行将文本附加到文件而不使用 io 重定向