Properties in Python

phil hunt philh at comuno.freeserve.co.uk
Wed Jun 20 09:51:28 EDT 2001


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?

-- 
##  Philip Hunt                   ##
##  philh at comuno.freeserve.co.uk  ##






More information about the Python-list mailing list