how to create a def that has the behaviour like a built-in keyword...

Joshua Macy l0819m0v0smfm001 at sneakemail.com
Sun Oct 7 10:33:20 EDT 2001


Niklas Frykholm wrote:

> It does make accessor functions look a bit nicer
> 
> 	print p.text
> 	p.text = "OK"
> 
> instead of
> 
> 	print p.getText()
> 	p.setText("OK")


   But the former is perfectly legal in Python:

 >>> class P:
... 
def __init__(self, text):
... 		self.text = text
...
 >>> p = P('spam')
 >>> print p.text
spam
 >>> p.text = "OK"
 >>> print p.text
OK
 >>>


What you can't do in Python (without playing __setattr__/__getattr__ 
tricks) is have fancy accessor functions that do calculations or have 
side-effects unless you're willing to use function syntax.  As long as 
you're content with simple attribute binding and lookup, though, your 
preferred syntax works.

Joshua




More information about the Python-list mailing list