"alex23" wrote: > Kalle Anke wrote: > > I'm coming to Python from other programming languages. I like to > > hide all attributes of a class and to only provide access to them > > via methods. > > I'm pretty fond of this format for setting up class properties: > > class Klass(object): > def propname(): > def fget: pass > def fset: pass > def fdel: pass > def doc: """pass""" > return locals() > propname = property(**propname()) > > (Replacing 'pass' in the getters & setters et.al with the actual > functionality you want, of course...) > > This method minimises the leftover bindings, effectively leaving the > getter/setter methods bound only to the property, ensuring they're only > called when the property is acted upon. > > Incidentally, kudos & thanks to whomever I originally stole it from :) > > -alex23
And a slight improvement in readability IMHO (for python 2.4+) is the following recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698. Using the Property decorator, the property declaration above becomes: class Klass(object): @Property # <--- the capitalized 'P' is not a typo def propname(): '''Documentation''' def fget: pass def fset: pass def fdel: pass The Property decorator peeks automagically the fget, fset, fdel and __doc__ from the property's locals(), instead of having the property return locals() explicitly. Also, it doesn't break when the property defines local variables other than [fget, fset, fdel, doc]. George -- http://mail.python.org/mailman/listinfo/python-list