2

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__?

amit kumar
  • 20,438
  • 23
  • 90
  • 126

2 Answers2

2

You can use

class Bunch:
    def __init__(self, **kwds):
        self.__dict__.update(kwds)

    def __setattr__(self, name, value):
        #do your verification stuff
        self.__dict__[name] = value

or with new-style class :

class Bunch(object):
    def __init__(self, **kwds):
        self.__dict__.update(kwds)

    def __setattr__(self, name, value):
        #do your verification stuff
        super(Bunch, self).__setattr__(name, value)
Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
1

No. You should define your class as class Bunch(object), but continue to refer to self.__dict__.

You only need to use the object.__setattr__ method while you are defining the self.__setattr__ method to prevent infinite recursion. __dict__ is not a method, but is an attribute on the object itself, so object.__dict__ would not work.

Jeremy
  • 1
  • 85
  • 340
  • 366
  • The part about `object.__dict__` is more or less clear. However, the reason for using `baseclass.__setattr__` seems to be to call the custom overload in the base class. Am I right? – amit kumar Jun 10 '11 at 11:41
  • I wouldn't say that you call the custom one in the base class. Since you're redefining how the "custom overload" method updates attributes, you can't use that method inside of itself. Since you're trying to update an attribute without going through your new custom mechanism, you refer to it from the base class instead. – Jeremy Jun 10 '11 at 11:44