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

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

问题描述

你知道,如果有一个内置的功能来构建一个字典从任意对象吗?我想要做这样的事情:

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.

感谢

推荐答案

请注意,在Python的当前版本的最佳实践是使用新型的类,即

Note that best practice in current versions of Python is to use new-style classes, 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}

此外,这取决于你想要做什么,这可能是不错的,从字典中继承。那么你的类的的字典,如果你愿意,你可以覆盖GETATTR和/或通过的setattr打电话,并设置字典。例如:

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天全站免登陆