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

前端 未结 2 470
长发绾君心
长发绾君心 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条回答
  •  -上瘾入骨i
    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())
    

提交回复
热议问题