Instead of the latter example, consider using the @property
decorator.
class MyClass(object):
def __init__(self):
super(MyClass, self).__init__()
self.__my_attr = 'My_Value'
@property
def my_attr(self):
return self.__my_attr
def doSomething(self):
localVariable = self.__my_attr
print localVariable
Use it only if you have good reason to protect the member, e.g. if you want to validate its values:
class Person:
@property
def age(self): return self.__age
@age.setter
def age(self, value):
if value < 0: raise Exception('Age out of bounds.')
self.__age = value
p = Person ()
p.age = 14
print (p.age)
p.age = -34