How to handle __setattr__ call from __init__?

I wrote a class that will be used to store parameters in a convenient way for etching. It overloads __setattr__ for easy access. It also uses a list to remember the order in which the attributes are added, so that the iteration order is predictable and constant. Here he is:

 class Parameters(object): def __init__(self): self._paramOrder = [] def __setattr__(self, name, value): self._paramOrder.append(name) object.__setattr__(self, name, value) def __delattr__(self, name): self._paramOrder.remove(name) object.__delattr__(self, name) def __iter__(self): for name in self._paramOrder: yield self.name def iteritems(self): for name in self._paramOrder: yield name, self.name 

The problem is that __init__ calls my overloaded __setattr__ to add _paramOrder to the instance dictionary. Is there a way to handle this without adding a special case to __setattr__ ?

+7
python
source share
2 answers

Yes.

ask for it instead of super(Parameters, self).__setattr__() .

 class Parameters(object): def __init__(self): super(Parameters, self).__setattr__('paramOrder', []) # etc. 

Or am I missing something?

Another alternative is to simply go straight to __dict__

 class Parameters(object): def __init__(self): self.__dict__['paramOrder'] = [] # etc. 

This should work because you are not overriding __getattr__ so you can read it without any clutter.

+7
source share

Use this line instead of __init__ :

 object.__setattr__(self, '_paramOrder', []) 
+3
source share

All Articles