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 with
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())
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:
class MyClass():
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:
class MyClass():
def __init__(self):
vars(self).update(a=dict(), b=dict(), c=dict())