I wonder if while working with OPP/Classes/Instances in Python I should be always using getAttr()/setAttr() 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?
Direct access to Class attr
class MyClass(object):
def __init__(self):
super(MyClass, self).__init__()
self.my_attr = 'My_Value'
def doSomething(self):
localVariable = self.my_attr
print localVariable
Using a Class's method to access a Class's attr
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
EDITED LATER:
While reading 'The Object-Oriented Thought Process' book (Matt Weisfeld : Developer's Library) ... The author states continuously throughout it:
"...Access to attributes within an object should be controlled by the object itself—no other object should directly change an attribute of another..."
"...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)..."
I will be sticking to setters and getters then. Suggested/mentioned here Python's @property and @.setter make it even easier.