[Tutor] object attribute validation
davea at davea.name
Sat Feb 23 03:35:13 CET 2013
On 02/22/2013 09:26 PM, Robert Sjoblom wrote:
>> 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 forgot to include the rest of the class as the OP defined it.
Therefore your conclusion is entirely wrong.
> You need a try/except, or some other form of validation here, otherwise:
>>>> b = Person("Johnny", "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.
You only need it for the setter, and it's there. The setter is called
by the initializer, through the call to property. Look up that mechanism.
More information about the Tutor