Dom, 2005-12-11 às 16:30 -0600, Ian Bicking escreveu: > Jim Fulton wrote: > >> Designing for inheritance > >> > >> Always decide whether a class's methods and instance variables > >> should be public or non-public. In general, never make data > >> variables public unless you're implementing essentially a > >> record. It's almost always preferrable to give a functional > > > > > interface to your class instead (and some Python 2.2 > > > developments will make this much nicer). > > > > > > Yes, Python 2.2 developments have made this better. Use of property() > > > should be suggested. > > > > This seems outdated. My impression, in part from time spent > > working with the Python Labs guys, is that it is fine to have public > > data sttributes even for non-"record" types. In fact, I would argue that > > any time you would be tempted to provide "getFoo()" and "setFoo(v)" > > for some "private attribute _foo", it would be better to make it > > public. I certainly find "blah.foo" and "blah.foo = v" to be much > > better than "blah.getFoo()" and blah.setFoo(v)". > > > > Certainly, properties provide a safety belt. I would argue it this > > way: Python APIs can include attributes as well as methods. > > Exposure of an attribute need not constrain the implementation, thanks > > to properties. OTOH, I wouldn't bother with a property unless it's needed. > > So, getting back to the original paragraph, perhaps it could say: > > Decide whether a class's methods and instance variables should be public > or non-public. Non-public methods and variables should start with an > underscore. > > Do not use accessor methods, like ``obj.getFoo()`` and > ``obj.setFoo(v)``, instead just expose a public attribute (``obj.foo``). > If necessary you can use ``property`` to implement the same > functionality that accessor methods would give you. If you do use > properties, getting that property should never have a side effect. > [well... I think that certain side effects like caching and logging are > okay, but I'm not sure how to make that distinction]
IMHO, if getting a property involves a potentially long computation, it's better to have an accessor method rather than a property; xpto.getFoobar() hints right away the programmer that to access that value some code has to be run, so the programmer is more likely to store the result in a temp variable for use in the same context, instead of calling it multiple times. Similar reasoning applites for setter vs property =. Regards, -- Gustavo J. A. M. Carneiro <[EMAIL PROTECTED]> <[EMAIL PROTECTED]> The universe is always one step beyond logic.
signature.asc
Description: Esta é uma parte de mensagem assinada digitalmente
_______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com