[Tutor] object attribute validation

Robert Sjoblom robert.sjoblom at gmail.com
Sat Feb 23 03:26:54 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. [snip] Following is my
> example code:

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

You need a try/except, or some other form of validation here, otherwise:

>>> b = Person("Johnny", "Six")
>>> b.get_age()
'Six'

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

I can't help you with that question, since I'm still (!) wrapping my
head around objects and haven't really gotten around to looking at
data validation and when/how you should do it. I would probably use
try/except for the __init__ and the setter.
-- 
best regards,
Robert S.


More information about the Tutor mailing list