using names before they're defined

Nick Vatamaniuc vatamane at gmail.com
Thu Jul 20 02:52:06 EDT 2006


Dave,

Python properties allow you to get rid of methods like c.getAttr(),
c.setAttr(v), c.delAttr() and replace them with simple constructs like
c.attr, c.attr=v and del c.attr.

If you have been using Java or C++ you know that as soon as you code
your class you have to start filling in the get() set()
delete()/reset() methods for each attribute. Some IDE tools like
Netbeans will to it for you with code refactoring and such. But for 10
attributes you will end up having another 20 or so
accessors/setters/and erase methods.

In Python not too long ago they introduced properties. With properties
you just access you attributes as attributes c.attr and c.attr=value if
you don't need to do anything special during getting and setting. Then
you can safely publish your API for everyone to use. If one day you
find a off-by-1 bug and you need to change one of the attributes when
it is accessed or set, you use properties. You create a method like
_get_attr(self) or _set_attr(self,v) in your class and at the end of
the class definition you write:
attr=property(_get_attr, _set_attr). From then on, when someone
accesses the attribute of your class c.attr the function _get_attr()
will be automatically called, in there you can do whatever you need and
return the value.

Check out this page:
http://www.python.org/download/releases/2.2/descrintro/
Look further down in the page for "properties".

Also take a look at "Python Is Not Java" article, it was interesting
for me to read. Properties getters and setters are mentioned there too
under the "getter and setters are Evil!" section ;)  Here is the link:
http://dirtsimple.org/2004/12/python-is-not-java.html

Nick V.

davehowey at f2s.com wrote:
> > Even if you need to do something during attachment of components it is
> > more Pythonic to use properties. So you will write a method in your
> > class name something like _set_up(self,upstream_obj) an  _get_up(self).
> >  And then at the end of your class put up=property(_get_up, _set_up).
> > You can still use the compr.up=... format.
>
> sorry, I don't quite follow. what are properties?
>
> > Also, you might want to re-think your OO design. It seem that all of
> > your components do a lot of things in common already. For one they all
> > are connected to other components like themselves, they also propably
> > will have method to do some computing, perhaps send or receive stuff
> > from other components, or they all will implement somekind of an event
> > model. In that case you could create a generic component class and
> > sublass the specific implementations from it.
>
> yes, I already do this - I have a component class and then the other
> components inherit from it.
> 
> Dave




More information about the Python-list mailing list