Right way to set variables at python class
<p>Which is the right way to work with variables inside a class?</p>

<p>1- setting them as class attributes where we get them and access them from class itself:</p>

<pre><code>class NeuralNetwork(object):

  def __init__(self, topology):
    self.topology = topology
    self.buildLayers()

  def buildLayers(self):
    for layer in self.topology:
      #do thing
</code></pre>

<p>2- passing them through methods that we need them without assign at class if they are not really useful variables:</p>

<pre><code>class NeuralNetwork(object):

  def __init__(self, topology):
    self.buildLayers(topology)

  def buildLayers(self, topology):
    for layer in topology:
      #do thing
</code></pre>

<p>3- a mix of the above two:</p>

<pre><code>class NeuralNetwork(object):

  def __init__(self, topology):
    self.topology = topology
    self.buildLayers(self.topology) # or self.buildLayers(topology) ?

  def buildLayers(self, topology):
    for layer in topology:
      #do thing
</code></pre>

<p>I think that the first one is the correct, but it don't let you to reuse the function for different purposes without assigning a new value to the variable, what would look like these:</p>

<pre><code>self.topology = x
self.buildLayers()
</code></pre>

<p>What looks weird and you don't really understand that changing <code>self.topology</code> is affecting the call of <code>self.buildLayers()</code></p>

<p>In general the first way is the "really object oriented" way, and much preferred over the second and the third.</p>

<p>If you want your buildLayers function to be able to change the topology occasionally, give it a param. topology with default value = None.</p>

<p>As long as you don't pass that param. at calling buildLayers, it will use this.topology. If you pass it, it will use the one you passed, and (if you wish) change this.topology to it.</p>

<p>By the way, while it's wise to stick to rules like this in the beginning, there are no real dogmas in programming. As experience grows, you'll find that to each rule there are many perfectly sane exceptions.</p>

<p>That's the fun of programming, you never stop learning from experience.</p>

python class variables standards