How to validate the __init__ parameters

Stephen Hansen apt.shansen at gmail.com
Mon Dec 21 12:50:57 EST 2009


On Mon, Dec 21, 2009 at 9:41 AM, Denis Doria <denisdoria at gmail.com> wrote:

> 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'
>
>
If I understand your requirements correctly-- you should just use
      self.foo = foo
in your __init__, as opposed to the backdoor
      self._foo = foo

Properties are probably the best way to get what you want, and if you want
to have the verification done, just don't bypass properties by assigning
into the private variable. Just because its fair-game for methods of a
class(and especially a classes initializer) to assign to the
"pseudo-private" member variables, doesn't mean it /has/ to or even /should/
:)

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091221/fb1b400d/attachment-0001.html>


More information about the Python-list mailing list