Python new-style-class-related question
-
26-10-2019 - |
Pergunta
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__
?
Solução
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.
Outras dicas
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)