Python字典从对象的字段 [英] Python dictionary from an object's fields
问题描述
>>> 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屋!