I have two classes in my code. first
is the parent, which second
inherits.
class first(object):
def __init(self,**kwargs):
pass
def __setattr__(self,name,value):
self.__dict__[name] = value
class second(first):
def do_something(self):
self.a = 1
self.b = 2
self.c = 3
when I am printing the class second (by e.g. second.__dict__
) I get the unordered dictionary. This is obvious. I want to change this behavior to get an ordered dictionary using the OrderedDict
class, but it does not work. I am changing implementation of first
in the following way:
class first(OrderedDict):
def __init__(self,**kwargs):
super(first,self).__init__(**kwargs)
def __setattr__(self,name_value):
super(first,self).__setattr__(name_value)
I would like to print second
using __dict__
or __repr__
, but I got the unordered dictionary. What should I change?
You can try by actually replacing __dict__ with OrderedDict:
This should printout:
I think the solutions in this thread focus too much on using
OrderedDict
as if it is a necessity. The class already has a builtin__dict__
method, the only problem is ordering the keys. Here is how I am retrieving(key, value)
pairs from my class in the order they are entered:I'm using a class to store about 70 variables used to configure and run a much bigger program. I save a text copy of the initial
(key, value)
pairs that can be used to initialize new instances of the class. I also save a text copy of the(key, value)
pairs after running the program because several of them are set or altered during the program run. Having the(key, value)
pairs in order simply improves the readability of the text file when I want to scan through the results.Another option; you can also manipulate new if you wish.
You can simply redirect all attribute access to an
OrderedDict
:Demo:
You can't otherwise replace the
__dict__
attribute with anOrderedDict
instance, because Python optimises instance attribute access by using the concrete class API to access the dictionary internals in C, bypassing theOrderedDict.__setitem__
hook altogether (see issue #1475692).