对象字段中的Python字典

2024-04-25 01:29:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

注意:不应包含方法。只有字段。


Tags: 对象方法函数helloworld字典foobar
3条回答

注意,Python2.7中的最佳实践是使用new-style类(Python3不需要)

class Foo(object):
   ...

而且,对象和类之间也有区别。要从任意对象构建字典,只需使用__dict__。通常,您将在类级别声明方法,在实例级别声明属性,因此__dict__应该没问题。例如:

>>> class A(object):
...   def __init__(self):
...     self.b = 1
...     self.c = 2
...   def do_nothing(self):
...     pass
...
>>> a = A()
>>> a.__dict__
{'c': 2, 'b': 1}

更好的方法(由注释中的robert建议)是内置的^{}函数:

>>> vars(a)
{'c': 2, 'b': 1}

或者,取决于你想做什么,从dict继承可能会更好。那么您的类已经是字典了,如果您想重写getattr和/或setattr来调用并设置dict

class Foo(dict):
    def __init__(self):
        pass
    def __getattr__(self, attr):
        return self[attr]

    # etc...

实际上,使用vars(x)比使用x.__dict__更像是Python。

内置的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

相关问题 更多 >