Instance variables vs. class variables in Python

后端 未结 4 856
我在风中等你
我在风中等你 2020-11-22 05:32

I have Python classes, of which I need only one instance at runtime, so it would be sufficient to have the attributes only once per class and not per instance. If there woul

4条回答
  •  长发绾君心
    2020-11-22 06:12

    When in doubt, you probably want an instance attribute.

    Class attributes are best reserved for special cases where they make sense. The only very-common use case is methods. It isn't uncommon to use class attributes for read-only constants that instances need to know (though the only benefit to this is if you also want access from outside the class), but you should certainly be cautious about storing any state in them, which is seldom what you want. Even if you will only have one instance, you should write the class like you would any other, which usually means using instance attributes.

提交回复
热议问题