overwrite set behavior

Wojtek Walczak gminick at bzt.bzt
Thu Sep 4 11:51:19 EDT 2008


On Thu, 4 Sep 2008 12:06:14 +0200, Marco Bizzarri wrote:

>> As far as I understand you, you need descriptors:
>> http://users.rcn.com/python/download/Descriptor.htm

> I know descriptors a litte, Wojtek, but didn't use them often; can you
> elaborate a little more on your idea?

Marco, I think that I misunderstood the OP, but I was thinking
about immutable (or set-once) attributes. Something like this:

---
class SetOnce(object):
   def __init__(self):
      self._attr1 = ""
      self._attr1flag = False

   def setatt(self, x):
      if self._attr1flag:
         raise ValueError("attribute already set")
      self._attr1flag = True
      self._attr1 = x

   def getatt(self):
      return self._attr1

   attr1 = property(getatt, setatt)

a = SetOnce()
a.attr1 = 1
print a.attr1
try:
   a.attr1 = 2
except ValueError:
   print a.attr1
---

$ python immutattr.py
1
1
$

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/



More information about the Python-list mailing list