Pythonic: use of __dict__ in the function self.__init__ of a class

前端 未结 2 471
长发绾君心
长发绾君心 2021-01-01 19:50

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

相关标签:
2条回答
  • 2021-01-01 20:26

    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())
    
    0 讨论(0)
  • 2021-01-01 20:46

    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())
    
    0 讨论(0)
提交回复
热议问题