On Jan 30, 5:03 pm, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > On 29 ene, 23:17, [EMAIL PROTECTED] wrote: > > > Property() can be used to rid ourselves of the extra effort of using > > two different methods (getAttrib() setAttrib()) for access of an > > attribute without giving direct access to the attribute, thus making > > it more elegant. So, the outsider using my module accesses the > > attribute with the syntax 'Object.attrib', but since this syntax looks > > as if he is accessing the attribute (rather than through a > > descrtiptor), should we subscribe to this syntax only when the > > attribute is both readable and writable? i.e., > > if I have an attribute which I strongly believe would always be only > > readable, should I go with the old style 'Object.getAttrib()'? > > Would like to know different perspectives. >
The use of accessor methods is generally eschewed in python because it is felt that reading and writing to foo.bar.baz, for instance, results in cleaner (more legible) code than the idiom using foo.getBar().getBaz()/foo.setBar().setBaz(). In the culture of some other 00 languages, directly accessing an object's method is considered a cardinal sin because it breaks encapsulation. The main practical problem cited is something along this scenario: You design an object to be used by others (objects or people), and include an attribute x. Without an accesor method the others would have to look directly at the attribute (ie via y = obj.x), which is all fine and good until you decide to change the implementation of your object, specifically you figure that x is really primary, but should rather be computed from a and b, so you want to remove attribute x and add a and b. Now with an accessor method getX(), all you need do is change it to return a+b (or whatever), whereas if you had relied on direct access, obviously all the other objects using your obj.x will need to change. Therefore it is said that other (objects and programmers) should be isolated from implentation details via accessor methods. Of course in python, should that situation arise, you simply employ property() and from the point of view of those others nothing has changed. In other words property() is a way of hiding implentation details when you need to. So we can happily access object attributes directly even if only apparently and enjoy clean code without guilt. -- http://mail.python.org/mailman/listinfo/python-list