How to validate the __init__ parameters
Denis Doria
denisdoria at gmail.com
Mon Dec 21 12:41:22 EST 2009
Hi;
I'm checking the best way to validate attributes inside a class. Of
course I can use property to check it, but I really want to do it
inside the __init__:
class A:
def __init__(self, foo, bar):
self.foo = foo #check if foo is correct
self.bar = bar
All examples that I saw with property didn't show a way to do it in
the __init__. Just to clarify, I don't want to check if the parameter
is an int, or something like that, I want to know if the parameter do
not use more than X chars; and want to do it when I'm 'creating' the
instance; not after the creation:
a = A('foo', 'bar')
not
class A:
def __init__(self, foo = None, bar = None):
self._foo = foo
self._bar = bar
def set_foo(self, foo):
if len(foo) > 5:
raise <something>
_foo = foo
foo = property(setter = set_foo)
a = A()
a.foo = 'foo'
I thought in something like:
class A:
def __init__(self, foo = None, bar = None):
set_foo(foo)
self._bar = bar
def set_foo(self, foo):
if len(foo) > 5:
raise <something>
_foo = foo
foo = property(setter = set_foo)
But looks too much like java
More information about the Python-list
mailing list