Denis Doria wrote:
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
One possible way, straight and simple
class A:
def __init__(self, foo = None, bar = None):
if len(foo) > 5:
raise ValueError('foo cannot exceed 5 characters')
self._foo = foo
self._bar = bar
JM
--
http://mail.python.org/mailman/listinfo/python-list