title: Python Classes Best Practices
body: <p>I wonder if while working with OPP/Classes/Instances in Python I should be always using <strong>getAttr()/setAttr()</strong> when reading-writing from-to a Class's attribute/variable. Or dealing with the variable/attribute directly (such as self.my_attr = "some_value") would be a better practice?</p>
  
  <h3><em>Direct access to Class attr</em></h3>
  
  <pre><code>class MyClass(object):
      def __init__(self):
          super(MyClass, self).__init__()
          self.my_attr = 'My_Value'
  
      def doSomething(self):
          localVariable = self.my_attr
          print localVariable
  </code></pre>
  
  <h3><em>Using a Class's method to access a Class's attr</em></h3>
  
  <pre><code>class MyClass(object):
      def __init__(self):
          super(MyClass, self).__init__()
          self.my_attr = 'My_Value'
  
      def getMyAttr(self):
          return self.my_attr
  
      def doSomething(self):
          localVariable = self.my_attr
          print localVariable
  </code></pre>
  
  <h1>EDITED LATER:</h1>
  
  <p>While reading 'The Object-Oriented Thought Process' book (Matt Weisfeld : Developer's Library) ... The author states continuously throughout it:</p>
  
  <p><em>"...Access to attributes within an object should be controlled by the object
  itself—no other object should directly change an attribute of another..."</em></p>
  
  <p><em>"...If you control the access to the attribute, when a problem arises, you do
  not have to worry about tracking down every piece of code that might have changed the
  attribute—it can only be changed in one place (the setter)..."</em> </p>
  
  <p>I will be sticking to setters and getters then. Suggested/mentioned here Python's @property and @.setter make it even easier.</p>