Attributes initialization/declaration in Python class: where to place them?

前端 未结 2 535
孤街浪徒
孤街浪徒 2020-12-05 01:57

I was wondering what was the best practice for initializing object attributes in Python, in the body of the class or inside the __init__ function?

i.e.<

2条回答
  •  情书的邮戳
    2020-12-05 02:17

    Attributes defined in the class definition are considered class variables (like static variables in Java), while those set in the initializer are instance attributes (note the difference between self.something = 1 and something = 1). See this question for more details, and this one for even more. There is not a lot of practical difference between these two cases, as the class-level definition gives the attribute a default value, but if you want to use some kind of logic to set an attribute before using an object instance you should do it in the __init__() method.

提交回复
热议问题