Since technically attributes are never private in Python, get/set methods are not considered "pythonic." This is the standard way to access object attributes:
class MyClass():
def __init__(self):
self.my_attr = 3
obj1 = MyClass()
print obj1.my_attr #will print 3
obj1.my_attr = 7
print obj1.my_attr #will print 7
You may, of course, still use getters and setters, and you can somewhat emulate private members by prepending __
to your attributes:
class MyClass():
def __init__(self):
self.__my_attr = 3
def set_my_attr(self,val):
self.__my_attr = val
def get_my_attr(self):
return self.__my_attr
obj1 = MyClass()
print obj1.get_my_attr() #will print 3
obj1.set_my_attr(7)
print obj1.get_my_attr() #will print 7
The __
"mangles" the variable name: from outside some class classname
in which __attr
is defined, __attr
is renamed as _classname__attr
; in the above example, instead of using the getters and setters, we could simply use obj1._MyClass__my_attr
. So __
discourages external use of attributes, but it doesn't prohibit it in the same way that the Java private
modifier does.
There are also, as you mention in your question, properties available in Python. The advantage of properties is that you can use them to implement functions that return or set values that, from outside the class, appear to be simply accessed as normal member attributes.