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

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

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


当前回答

使用__dict__的一个缺点是它很浅;它不会将任何子类转换为字典。

如果你使用的是Python3.5或更高版本,你可以使用jsons:

>>> import jsons
>>> jsons.dump(f)
{'bar': 'hello', 'baz': 'world'}

其他回答

内置的dir会给你所有对象的属性,包括特殊的方法,如__str__, __dict__和一大堆你可能不想要的其他方法。但是你可以这样做:

>>> class Foo(object):
...     bar = 'hello'
...     baz = 'world'
...
>>> f = Foo()
>>> [name for name in dir(f) if not name.startswith('__')]
[ 'bar', 'baz' ]
>>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__')) 
{ 'bar': 'hello', 'baz': 'world' }

所以可以扩展它,只返回数据属性,而不返回方法,通过定义你的props函数:

import inspect

def props(obj):
    pr = {}
    for name in dir(obj):
        value = getattr(obj, name)
        if not name.startswith('__') and not inspect.ismethod(value):
            pr[name] = value
    return pr

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

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

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

正如上面的一条评论中提到的,vars目前不是通用的,因为它不适用于具有__slots__而不是普通__dict__的对象。此外,一些对象(例如,str或int等内置对象)既没有__dict__也没有__slots__。

目前,一个更通用的解决方案可能是:

def instance_attributes(obj: Any) -> Dict[str, Any]:
    """Get a name-to-value dictionary of instance attributes of an arbitrary object."""
    try:
        return vars(obj)
    except TypeError:
        pass

    # object doesn't have __dict__, try with __slots__
    try:
        slots = obj.__slots__
    except AttributeError:
        # doesn't have __dict__ nor __slots__, probably a builtin like str or int
        return {}
    # collect all slots attributes (some might not be present)
    attrs = {}
    for name in slots:
        try:
            attrs[name] = getattr(obj, name)
        except AttributeError:
            continue
    return attrs

例子:

class Foo:
    class_var = "spam"


class Bar:
    class_var = "eggs"
    
    __slots__ = ["a", "b"]
>>> foo = Foo()
>>> foo.a = 1
>>> foo.b = 2
>>> instance_attributes(foo)
{'a': 1, 'b': 2}

>>> bar = Bar()
>>> bar.a = 3
>>> instance_attributes(bar)
{'a': 3}

>>> instance_attributes("baz") 
{}


咆哮:

遗憾的是,这还没有内置到vars中。Python中的许多内建承诺是问题的“解决方案”,但总有一些特殊情况没有得到处理……在任何情况下,最终都必须手动编写代码。

要从任意对象构建字典,使用__dict__就足够了。

这将遗漏对象从其类继承的属性。例如,

class c(object):
    x = 3
a = c()

Hasattr (a, 'x')为真,但'x'没有出现在a.__dict__中

我想我应该花点时间向您展示如何通过dict(obj)将对象转换为dict。

class A(object):
    d = '4'
    e = '5'
    f = '6'

    def __init__(self):
        self.a = '1'
        self.b = '2'
        self.c = '3'

    def __iter__(self):
        # first start by grabbing the Class items
        iters = dict((x,y) for x,y in A.__dict__.items() if x[:2] != '__')

        # then update the class items with the instance items
        iters.update(self.__dict__)

        # now 'yield' through the items
        for x,y in iters.items():
            yield x,y

a = A()
print(dict(a)) 
# prints "{'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4', 'f': '6'}"

这段代码的关键部分是__iter__函数。

正如注释所解释的,我们要做的第一件事是抓取Class项,并防止任何以'__'开头的内容。

一旦创建了字典,就可以使用update dict函数并传入实例__dict__。

这将为您提供一个完整的类+实例成员字典。现在剩下的就是遍历它们并产生返回值。

另外,如果你计划经常使用这个,你可以创建一个@iterable类装饰器。

def iterable(cls):
    def iterfn(self):
        iters = dict((x,y) for x,y in cls.__dict__.items() if x[:2] != '__')
        iters.update(self.__dict__)

        for x,y in iters.items():
            yield x,y

    cls.__iter__ = iterfn
    return cls

@iterable
class B(object):
    d = 'd'
    e = 'e'
    f = 'f'

    def __init__(self):
        self.a = 'a'
        self.b = 'b'
        self.c = 'c'

b = B()
print(dict(b))