Alan Gauld wrote: > This is fine and dandy but what if we want to find out the > current value of a.value without calling inc? > Thats where hetter/setter/direct access comes into the > picture. > In Java and some other languages the idiomatic thing > to do is provide methods prefixed with get/set for each attribute > > class Counter(object): > def __init__(self, initial=0, delta=1):... > def inc(self)... > def state(self):... > def getDelta(self): return self.delta > def getValue(self): return self.value > def setValue(self, val): self.value = val > def setDelta(self, val): self.delta = val > > Now this is a lot of typing! It also isn't necessary in Python > because Python allows you to access the attributes > diectly - direct access.
To amplify and clarify a little: - Other languages can also give direct access to attributes, this is not unique to Python. Java and C++, at least (the languages I know), also have a way to *restrict* direct access to attributes which Python does not really have. - There is a good reason for using setters and getters in Java and C++ - they have no way to convert an attribute access into a method call. So if you start with attribute access and then realize you want to add some code to the access, you are stuck - you have to change the interface to the class. Python does not have this problem - attribute access can be converted to a method call using properties. For this reason, there is IMO (and as generally accepted usage) no advantage to using getters & setters in Python for simple attribute access. Introduction to properties: http://personalpages.tds.net/~kent37/kk/00008.html - Python does have a convention for documenting which attributes (including methods) are considered part of the public interface and which are not. Non-public attribute names are prefixed with _ (single underscore). This is a signal to users of the class that the attribute is considered an internal implementation detail and to use it at your own risk. This is consistent with the Python philosophy that "we're all consenting adults here" - i.e. that the users of a class don't need to be protected from shooting themselves in the foot - it is enough to put a warning sign on the gun and the foot :-) Kent _______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
