[Tutor] object attribute validation

neubyr neubyr at gmail.com
Sat Feb 23 00:50:06 CET 2013


I would like to validate data attributes before the object is instantiated
or any changes thereafter. For example, following is a simple Person class
with name and age attributes. I would like to validate whether age is an
integer before it is added/changed in the object's dictionary. I have taken
a simple integer validation example, but it could be something like
DateField validation or X509 certificate validation as well. Following is
my example code:


class Person(object):
  def __init__(self,name,age):
    self.name = name
    self.age = age

  def get_age(self):
    return self._age

  def set_age(self,val):
    try:
      int(val)
      self._age = val
    except ValueError:
        raise Exception('Invalid value for age')

  def del_age(self):
    del self._age

  age = property(get_age,set_age,del_age)

a = Person('John',6)
b = Person('Johny','Six')


Is this a good approach? Any suggestions for improving the code or
alternative approaches would be helpful.


-- thanks,
   neubyr
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130222/b2ddd20f/attachment.html>


More information about the Tutor mailing list