您知道是否有一个内置函数可以从任意对象构建字典吗?我想这样做:

>>> class Foo:
...     bar = 'hello'
...     baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }

注意:它不应该包括方法。只有字段。


当前回答

Try:

from pprint import pformat
a_dict = eval(pformat(an_obj))

其他回答

使用vars(x)而不是x.__dict__实际上更python化。

我给出了两个答案的组合:

dict((key, value) for key, value in f.__dict__.iteritems() 
    if not callable(value) and not key.startswith('__'))

回答晚了,但为了完整性和谷歌人的利益:

def props(x):
    return dict((key, getattr(x, key)) for key in dir(x) if key not in dir(x.__class__))

这将不会显示类中定义的方法,但仍然会显示字段,包括那些分配给lambdas的字段或那些以双下划线开头的字段。

如果你想列出部分属性,重写__dict__:

def __dict__(self):
    d = {
    'attr_1' : self.attr_1,
    ...
    }
    return d

# Call __dict__
d = instance.__dict__()

如果你的实例得到一些大的块数据,并且你想把d推到Redis消息队列中,这很有帮助。

Python3.x

return dict((key, value) for key, value in f.__dict__.items() if not callable(value) and not key.startswith('__'))