来自对象字段的Python字典

时间:2008-09-14 18:00:43

标签: python dictionary attributes object metaprogramming

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

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

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

14 个答案:

答案 0 :(得分:353)

请注意,Python 2.7中的最佳实践是使用 new-style 类(Python 3不需要),即

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函数:

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

或者,根据您想要做的事情,从dict继承可能会很好。然后你的班级已经一个字典,如果你想要,你可以覆盖getattr和/或setattr来打电话并设置字典。例如:

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

    # etc...

答案 1 :(得分:108)

而不是x.__dict__,使用vars(x)实际上更具pythonic。

答案 2 :(得分:55)

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

答案 3 :(得分:24)

我已经确定了两个答案的组合:

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

答案 4 :(得分:15)

  

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

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

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

hasattr(a,'x')为真,但'x'没有出现在.__ dict __

答案 5 :(得分:13)

我以为我需要一些时间来向您展示如何通过dict(obj)将对象翻译为词典。

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项目并防止以' __'开头的任何内容。

一旦您创建了dict,就可以使用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))

答案 6 :(得分:7)

迟到的答案,但提供了完整性和googlers的好处:

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

这不会显示在类中定义的方法,但它仍会显示包含分配给lambdas的字段或以双下划线开头的字段。

答案 7 :(得分:4)

我认为最简单的方法是为类创建 getitem 属性。如果您需要写入对象,则可以创建自定义 setattr 。以下是 getitem 的示例:

class A(object):
    def __init__(self):
        self.b = 1
        self.c = 2
    def __getitem__(self, item):
        return self.__dict__[item]

# Usage: 
a = A()
a.__getitem__('b')  # Outputs 1
a.__dict__  # Outputs {'c': 2, 'b': 1}
vars(a)  # Outputs {'c': 2, 'b': 1}

dict 将对象属性生成到字典中,字典对象可用于获取所需的项目。

答案 8 :(得分:4)

vars()很好,但不适用于对象的嵌套对象

将对象的嵌套对象转换为dict:

def to_dict(self):
    return json.loads(json.dumps(self, default=lambda o: o.__dict__))

答案 9 :(得分:3)

如果要列出部分属性,请覆盖__dict__

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

# Call __dict__
d = instance.__dict__()

如果您的instance获取了一些大型数据块并且您希望将d推送到Redis之类的消息队列,这会有很大帮助。

答案 10 :(得分:3)

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

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

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

答案 11 :(得分:1)

one of the comments above 中所述,vars 目前不是通用的,因为它不适用于带有 __slots__ 而不是普通 __dict__ 的对象。此外,一些对象(例如,像 strint 这样的内置函数)两者都没有 __dict__ nor __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 中的许多内置函数都承诺是问题的“解决方案”,但总有一些特殊情况没有得到处理......而且最终不得不在任何情况下手动编写代码。

答案 12 :(得分:1)

在 2021 年,对于嵌套对象/dicts/json 使用 pydantic BaseModel - 将嵌套的 dicts 和嵌套的 json 对象转换为 python 对象和 JSON,反之亦然:

https://pydantic-docs.helpmanual.io/usage/models/

class Base {
    test = "TEST";

    _build<T extends { [key in keyof this]?: boolean | ((key: key) => unknown) }>(keys?: T) {
        const obj: {
            [K in keyof T]?: T[K] extends true ? this[K] : T[K] extends (...args: any) => any ? ReturnType<T[K]> : never
         } = {}
        for (const key in keys) {
            const meta = keys[key];
            if (typeof meta === "function") {
                obj[key] = meta(key);
            } else if (meta === true) {
                obj[key] = this[key];
            }
        }
        return obj;
    }
}

const base = new Base()

const d = base._build({ test: (x /* x = Base.test */) => x + "test" }) // { test: "TESTtest" } // { test: string }
base._build({ test: true }) // { test: "TEST" } // { test: string }
const f = base._build({test: false}) // {} empty

d.test;

f.test;
f.test;

要听写的对象

>>> class Foo(BaseModel):
...     count: int
...     size: float = None
... 
>>> 
>>> class Bar(BaseModel):
...     apple = 'x'
...     banana = 'y'
... 
>>> 
>>> class Spam(BaseModel):
...     foo: Foo
...     bars: List[Bar]
... 
>>> 
>>> m = Spam(foo={'count': 4}, bars=[{'apple': 'x1'}, {'apple': 'x2'}])

JSON 对象

>>> print(m.dict())
{'foo': {'count': 4, 'size': None}, 'bars': [{'apple': 'x1', 'banana': 'y'}, {'apple': 'x2', 'banana': 'y'}]}

直接反对

>>> print(m.json())
{"foo": {"count": 4, "size": null}, "bars": [{"apple": "x1", "banana": "y"}, {"apple": "x2", "banana": "y"}]}

JSON 到对象

>>> spam = Spam.parse_obj({'foo': {'count': 4, 'size': None}, 'bars': [{'apple': 'x1', 'banana': 'y'}, {'apple': 'x2', 'banana': 'y2'}]})
>>> spam
Spam(foo=Foo(count=4, size=None), bars=[Bar(apple='x1', banana='y'), Bar(apple='x2', banana='y2')])

答案 13 :(得分:0)

PYTHON 3:

class DateTimeDecoder(json.JSONDecoder):

   def __init__(self, *args, **kargs):
        JSONDecoder.__init__(self, object_hook=self.dict_to_object,
                         *args, **kargs)

   def dict_to_object(self, d):
       if '__type__' not in d:
          return d

       type = d.pop('__type__')
       try:
          dateobj = datetime(**d)
          return dateobj
       except:
          d['__type__'] = type
          return d

def json_default_format(value):
    try:
        if isinstance(value, datetime):
            return {
                '__type__': 'datetime',
                'year': value.year,
                'month': value.month,
                'day': value.day,
                'hour': value.hour,
                'minute': value.minute,
                'second': value.second,
                'microsecond': value.microsecond,
            }
        if isinstance(value, decimal.Decimal):
            return float(value)
        if isinstance(value, Enum):
            return value.name
        else:
            return vars(value)
    except Exception as e:
        raise ValueError

现在您可以在自己的类中使用上面的代码:

class Foo():
  def toJSON(self):
        return json.loads(
            json.dumps(self, sort_keys=True, indent=4, separators=(',', ': '), default=json_default_format), cls=DateTimeDecoder)


Foo().toJSON()