How to get/set class attributes in Python

alex23 wuwei23 at
Sun Jun 12 06:56:42 EDT 2005

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 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 :)


More information about the Python-list mailing list