迭代python中的对象属性 [英] Iterate over object attributes in python

查看:23
本文介绍了迭代python中的对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

class my_python_obj(object):attr1='a'attr2='b'attr3='c'def method1(自我等):#声明

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

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

只是为了让事情更清楚:

def to_dict(self):'''这是我已经拥有的'''d={}d["attr1"]= self.attr1d["attr2"]= self.attr2d["attr3"]= self.attr3返回

·

def to_dict(self):'''这就是我想做的'''d={}对于 my_python_obj.attributes 中的 v:d[v] = self.v返回

更新:对于属性,我指的只是这个对象的变量,而不是方法.

解决方案

假设你有一个类如

<预><代码>>>>类 Cls(对象):... foo = 1... bar = '你好'... def func(self):...返回给我打电话"...>>>obj = Cls()

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

<预><代码>>>>目录(对象)['__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) 如果不是 a.startswith('__')]['bar', 'foo', 'func']

或者如果您更喜欢地图/过滤器.

<预><代码>>>>过滤器(lambda a:不是 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']

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

<预><代码>>>>设置(目录(Cls)) - 设置(目录(对象))set(['__module__', 'bar', 'func', '__dict__', 'foo', '__weakref__'])

I have a python object with several attributes and methods. I want to iterate over object attributes.

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

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

I want to generate a dictionary containing all of the objects attributes and their current values, but I want to do it in a dynamic way (so if later I add another attribute I don't have to remember to update my function as well).

In php variables can be used as keys, but objects in python are unsuscriptable and if I use the dot notation for this it creates a new attribute with the name of my var, which is not my intent.

Just to make things clearer:

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

Update: With attributes I mean only the variables of this object, not the methods.

解决方案

Assuming you have a class such as

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

calling dir on the object gives you back all the attributes of that object, including python special attributes. Although some object attributes are callable, such as methods.

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

You can always filter out the special methods by using a list comprehension.

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

or if you prefer map/filters.

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

If you want to filter out the methods, you can use the builtin callable as a check.

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

You could also inspect the difference between your class and its instance object using.

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

这篇关于迭代python中的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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