Should I use “self” to define variables / objects of class instanced which I will not need to reach from the outside?

前端 未结 3 703
春和景丽
春和景丽 2021-02-06 10:14

I am not a complete beginner but fairly new to Python. Whilst working on a project today I just had an idea and wondered regarding the usage of \"self

3条回答
  •  执念已碎
    2021-02-06 10:36

    If you dont use self.some_temp_var, then you are defining a local variable which will be garbage collected after the constructor.

    So yes you need self if you want to define an instance attribute that should persist with the instance. Whether you need it to be public or private is a matter of naming. Prefix it with an _ for protected or __ for private.

    If some_temp_var is just a temp for the constructor and you never need it again then no, you dont need self. It is about persistence and member attributes. You do not need self for the pure fact of working with a variable within a single method.

    Consider this... What if some_temp_var were some huge data structure that you build up to arrive at the real result value? You dont want to use self to store a temp variable because it wont free memory until you delete it or the instance. You want it to be cleaned up when it is no longer needed.

提交回复
热议问题