Properties in Python
Steve Holden
sholden at holdenweb.com
Wed Jun 20 18:20:49 EDT 2001
"phil hunt" <philh at comuno.freeserve.co.uk> wrote in message
news:slrn9j1aj0.893.philh at comuno.freeserve.co.uk...
> On Wed, 20 Jun 2001 02:04:33 GMT, Peter Caven <p.caven at ieee.org> wrote:
> >I'm sure that many people reading this newsgroup are aware that the C#
> >(C-Sharp) language has a syntax for 'Properties' that allows a class
> >implementor to hide the implementation of an instance's attribute behind
a
> >'get'/'set' interface.
> >In Python terms this would look like:
> >
> >class Demo:
> > def __init__(self):
> > self.attr1 = 1
> > self.attr2 = 2
> >
> > def AMethod(self):
> > pass
> >
> >and where:
> >
> >d = Demo()
> >a1 = d.attr1 # would actually execute something like: d.attr1.get()
> >d.attr2 = 3 # would actually execute something like:
d.attr2.set(3)
> >
> >So, instead of allowing direct access to the instance attributes, C#
> >actually executes 'get' and 'set' methods (if defined) for the
attributes.
> >This lets a programmer change the behavior of the attributes defined in
the
> >class (to have side-effects for example) without changing any code
written
> >by users of the class.
> >
> >Does anyone have any ideas on how to do this (elegantly) in Python?
>
> Yes:
>
> class Demo:
> def __init__(self):
> self.attr1 = 1
> self.attr2 = 2
>
> def getAttr1(self): return self.attr1
> def setAttr1(self, v): self.attr1 = v
>
> def getAttr2(self): return self.attr2
> def setAttr2(self, v): self.attr2 = v
>
> What's so hard about that?
>
I think the intention was to hide the mechanism under standard assignment,
as (for example) Delphi allows you to do for Pascal. In that way it appears
you are assigning to/from properties, but the language actually invokes the
appropriate logic (which can do much more than read or set a variable)
automagically.
regards
sTEVE
More information about the Python-list
mailing list