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

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

问题描述

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

 >>> Foo类:
... bar ='hello'
... baz ='world'
...
>>> f = Foo()
>>>道具(f)
{'bar':'hello','baz':'world'}

注意:不应包含方法。

解决方案

请注意,当前版本的Python的最佳做法是使用新风格类,即

  class Foo(object):
...

此外,对象和类之间有区别。要从任意的对象构建字典,使用 __ dict __ 就足够了。通常,您将在类级别声明您的方法,并在实例级别声明您的属性,因此 __ dict __ 应该是正常的。例如:

 >>> A类(对象):
... def __init __(self):
... self.b = 1
... self.c = 2
... def do_nothing(self):
... pass
...
>>> a = A()
>>>> a .__ dict__
{'c':2,'b':1}

,取决于你想做什么,可能会很好的继承从dict。然后,你的类已经是一个字典,如果你想要你可以覆盖getattr和/或setattr来调用和设置dict。例如:

  class Foo(dict):
def __init __(self):
pass
def __getattr __(self,attr):
return self [attr]

#etc ...


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

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