Dan Sommers <[EMAIL PROTECTED]> wrote: > On 28 Feb 2005 10:30:03 GMT, > Nick Craig-Wood <[EMAIL PROTECTED]> wrote: > > > Actually I would say just access the attribute directly for both get > > and set, until it needs to do something special in which case use > > property(). > > > The reason why people fill their code up with boiler plate get/set > > methods is to give them the flexibility to change the implementation > > without having to change any of the users. In python you just swap > > from direct attribute access to using property(). > > The reason their code is so inflexible is that they've filled their > classes with boiler plate get/set methods.
Amen to that! As programmers we abhor code duplication, and boiler plate is just code duplication. Even if your fancy editor adds it for you ;-) > Why do users of classes need such access anyway? If my class performs > useful functions and returns useful results, no user of my class should > care about its attributes. If I "have to" allow access to my attributes > in order that my users be happy, then I did something else wrong when I > designed the class and its public interface in the first place. I would say this is an excellent philosphy for C++ or Java. When I'm writing C++ I try to keep the attributes private. I try not to make accessor methods at all until absolutely necessary. I always think I've failed if I end up writing getBlah and setBlah methods. In C++ its always in the back of my mind that an inline accessor method will get optimised into exactly the same code as accessing the attribute directly anyway. > I usually aim for this: if users of the public interface of my class > can figure out that I changed the implementation, then I've exposed too > much. Sure there are exceptions, but that's my basic thought process. However in python, there is no harm in accessing the attributes directly. You can change the implementation whenever you like, and change the attributes into property()s and the users will never know. And, as another poster pointed out - you are already accessing the instance variables just by calling its methods, so you shouldn't feel too squeamish! Read only attributes are easy to understand, unlikely to go wrong and faster than getBlah() accessor methods. Writable attributes I think are good candidates for methods though. Looking inside an object is one thing but changing its internal state is another and should probably be done through a defined interface. > Sorry about the rant. I wouldn't call that a rant, it was quite polite compared to some of the threads on c.l.p recently ;-) -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list