Skip to content Skip to sidebar Skip to footer

Pythonic: Use Of __dict__ In The Function Self.__init__ Of A Class

While coding a new class with the spyder IDE, and using pylint to check the final result, I've ran into error messages (but the code work as expected without error). Context: in th

Solution 1:

Yes, it is reasonable to update the instance dictionary directly. Alternatively, you can use setattr to update the variables. I've seen both approaches used in production code.

With setattr there is no need to touch the instance dictionary directly:

classMyClass():
    def__init__(self):
        for var in'a', 'b', 'c':
            setattr(self, var, dict())

But if you update the instance dictionary directly, there are couple possible improvements to consider. For example, using vars() instead of __dict__ is a bit nicer looking. Also, you can use the dict.update method with keyword arguments:

classMyClass():
    def__init__(self):
        vars(self).update(a=dict(), b=dict(), c=dict())

Solution 2:

It is indeed fine, but I it's generally recommended to avoid messing with __dict__ directly. What if, for example, you want to put a custom setter for an attribute of your object later down the road?

In your example case, you could simply replace the line in your for loop with the following:

setattr(self, _var, dict())

Post a Comment for "Pythonic: Use Of __dict__ In The Function Self.__init__ Of A Class"