How to prevent illegal definition of a variable in objects?

david_ullrich at my-deja.com david_ullrich at my-deja.com
Thu Jun 15 13:19:12 EDT 2000


In article <20000614155102.E16232 at freei.com>,
  Sean Blakey <sblakey at freei.net> wrote:
> On Wed, Jun 14, 2000 at 05:48:45PM -0400, Daehyok Shin wrote:
> > How can I prevent illegal definition of a variable to an object?
> > For instance,
> >
> > class A:
> >     __init__(self):
> >             self.x = 1
> >
> >     __setattr__(self, name, value):
> >             if name == "x":
> >                     self.x = value
> >             else:
> >                 raise AttributeException
> >
> >     __getattr__(self, name):
> >             if name == "x":
> >                 return self.x
> >             else:
> >                 raise AttributeException
> >
> > >>> a = A()
> > >>> a.x = 10
> > >>> a.y = 20 # I want to raise an AttributeException.
> >
> > Peter
> >
> >
> > --
> > http://www.python.org/mailman/listinfo/python-list
>
> The code you posted seems to do what you want, provided you
> a)add the 'def' keyword to your function definitions
>     and
> b) define AttributeException (perhaps you meant AttributeError?)

   That's the way it seems all right, until you consider the
fact that the line "self.x = value" is going to call the
__setattr__ method... (I imagine this has been pointed out
already but I don't see it below - seems worth mentioning
explicitly for the benefit of anyone who doesn't see the
problem.)

> --
> Sean Blakey, sblakey at freei.com
> Software Developer, FreeInternet.com
> (253)796-6500x1025
> 	"Uncle Cosmo ... why do they call this a word processor?"
> 	"It's simple, Skyler ... you've seen what food processors do to
food,
> right?"
> 		-- MacNelley, "Shoe"
>
>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list