Python dictionary from an object's fields -
do know if there built-in function build dictionary arbitrary object? i'd this:
>>> class foo: ... bar = 'hello' ... baz = 'world' ... >>> f = foo() >>> props(f) { 'bar' : 'hello', 'baz' : 'world' }
note: should not include methods. fields.
note best practice in python 2.7 use new-style classes (not needed python 3), i.e.
class foo(object): ...
also, there's difference between 'object' , 'class'. build dictionary arbitrary object, it's sufficient use __dict__
. usually, you'll declare methods @ class level , attributes @ instance level, __dict__
should fine. example:
>>> class a(object): ... def __init__(self): ... self.b = 1 ... self.c = 2 ... def do_nothing(self): ... pass ... >>> = a() >>> a.__dict__ {'c': 2, 'b': 1}
a better approach (suggested robert in comments) builtin vars
function:
>>> vars(a) {'c': 2, 'b': 1}
alternatively, depending on want do, might nice inherit dict
. class already dictionary, , if want can override getattr
and/or setattr
call through , set dict. example:
class foo(dict): def __init__(self): pass def __getattr__(self, attr): return self[attr] # etc...
Comments
Post a Comment