来自对象字段的 Python 字典 [英] Python dictionary from an object's fields

查看:28
本文介绍了来自对象字段的 Python 字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你知道有没有内置函数可以从任意对象构建字典?我想做这样的事情:

<预><代码>>>>Foo类:... bar = '你好'... baz = '世界'...>>>f = Foo()>>>道具(f){'bar':'你好','baz':'世界'}

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

解决方案

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

class Foo(object):...

此外,对象"和类"之间也有区别.要从任意对象构建字典,使用__dict__就足够了.通常,你会在类级别声明你的方法,在实例级别声明你的属性,所以 __dict__ 应该没问题.例如:

>>>A类(对象):... def __init__(self):... self.b = 1... self.c = 2... def do_nothing(self):...     经过...>>>a = A()>>>a.__dict__{'c':2,'b':1}

更好的方法(由 robert 在评论中建议)是内置的 vars 函数:

>>>变量(一){'c':2,'b':1}

或者,根据您想要做什么,从 dict 继承可能会很好.那么你的类已经是一个字典,如果你愿意,你可以覆盖 getattr 和/或 setattr 来调用并设置字典.例如:

class Foo(dict):def __init__(self):经过def __getattr__(self, attr):返回自我[attr]# 等等...

Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:

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

NOTE: It should not include methods. Only fields.

解决方案

Note that best practice in Python 2.7 is to use new-style classes (not needed with Python 3), i.e.

class Foo(object):
   ...

Also, there's a difference between an 'object' and a 'class'. To build a dictionary from an arbitrary object, it's sufficient to use __dict__. Usually, you'll declare your methods at class level and your attributes at instance level, so __dict__ should be fine. For example:

>>> 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}

A better approach (suggested by robert in comments) is the builtin vars function:

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

Alternatively, depending on what you want to do, it might be nice to inherit from dict. Then your class is already a dictionary, and if you want you can override getattr and/or setattr to call through and set the dict. For example:

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

    # etc...

这篇关于来自对象字段的 Python 字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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