Note that there are some explanatory texts on larger screens.

plurals
  1. POShould I use "self" to define variables / objects of class instanced which I will not need to reach from the outside?
    primarykey
    data
    text
    <p>I am not a complete beginner but fairly new to <strong>Python</strong>. Whilst working on a project today I just had an idea and wondered regarding the usage of "<strong>self</strong>"; about which I've been reading for the past some while and I still can not figure out if it's always necessary or not. My question solely concerns instances of classes and instance parameters/variables. <strong>This question is not about Class Variables which affect all instances</strong>.</p> <p><strong>Example</strong>:</p> <pre><code>class C: def __init__(self, parent = None): super(C, self).__init__(parent) self.some_temp_var = AnotherClass() self.important_property = self.some_temp_var.bring_the_jewels() ins_c = C() print ins_c.important_property </code></pre> <p>In the above code, I use <strong>self</strong> before both variable declarations (<strong>some_temp_var</strong> and <strong>important_property</strong>).</p> <p>I <strong>will need to access</strong> **important_property** later from the outside (where instance's been created) and maybe even modify it.</p> <p>But I will not need access to the instance of AnotherClass() and/or variable pointing to it (<strong>some_temp_var</strong>). I just need an instance of it class once, and I need to execute its method bring_the_jewels only once to populate value of <strong>important_property</strong>. </p> <p>Should I still use self before declaring that variable as well?</p> <pre><code>self.some_temp_var = .... self.important_property = .... </code></pre> <p>or can it be:</p> <pre><code>some_temp_var = .... self.important_property = .... </code></pre> <p>Thank you for your help.</p> <p><em>Ps. I did my research in a length way. Due to lack of my English and/or CS knowledge, I may not have found a currently existing duplicate however I did search and I did search a lot. Before calling this question "duplicate" or "not constructive" please read it throughly. This is a question with clear answer and it's very important, and complicated matter. Thank you for your understanding.</em></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload