I am a python learner and currently hacking up a class with variable number of fields as in the “Bunch of Named Stuff” example here.
class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
I also want to write a __setattr__ in this class in order to check the input attribute name. But, the python documentation says,
If __setattr__() wants to assign to an
instance attribute, it should not
simply execute “self.name = value” —
this would cause a recursive call to
itself. Instead, it should insert the
value in the dictionary of instance
attributes, e.g., “self.__dict__[name]
= value”.
For new-style classes, rather than
accessing the instance dictionary, it
should call the base class method with
the same name, for example,
“object.__setattr__(self, name,
value)”.
In that case, should I also use object.__dict__ in the __init__ function to replace self.__dict__?
No. You should define your class as
class Bunch(object), but continue to refer toself.__dict__.You only need to use the
object.__setattr__method while you are defining theself.__setattr__method to prevent infinite recursion.__dict__is not a method, but is an attribute on the object itself, soobject.__dict__would not work.