A matter of style: class.foo = bar vs. class.set_foo(bar)

Delaney, Timothy tdelaney at avaya.com
Sat Nov 11 19:50:34 EST 2000


> But best of all is that in the worst case, when I guess wrong about
> spam.foo = bar and find I have to change the functionality
> significantly, probably to work around a design flaw or 
> something, I can
> always pull out __setattr__ and redirect the assignment to a method
> call.  Rather than rewriting piles of code that used the original
> simpler assignment, risking injection of new bugs, I quietly fix the
> problem and carry on with my work.  
> 
> And come to think of it, with Delphi I probably had the same 
> option, but
> it was Python (plus a little XP) which inspired this most pragmatic
> approach.

That's the true magic of properties - it adds another way of changing the
implementation without changing the interface.

I was so impressed with Delphi properties (quite some time ago now) that I
wrote a C++ property template class. It was a *lot* harder to get right than
using __getattr__/__setattr__ in Python, which is much harder than using
properties in Delphi where it is explicitly supported by the language.

I would actully quite like to see a standard syntax in Python for this.

class C

	def __init__(self)
		self.fX = None

	def setX (self, value)
		self.fX = value

	def getX (self)
		return self.fX

	property x(getX, setX)
	property x_readOnly(getX, None)
	property x_writeOnly(None, setX)

C.x = 1		# OK
print C.x		# prints 1
x_readOnly = 2	# Throws exception
print x_writeOnly	# Throws exception

but it's *definitely* not ready for a PEP yet.

Tim Delaney
Avaya Australia
+61 2 9532 9079




More information about the Python-list mailing list