How to prevent illegal definition of a variable in objects?
Daehyok Shin
sdhyok at email.unc.edu
Wed Jun 14 21:53:05 EDT 2000
Maybe a little better, but not enough good.
class A:
x = 1
def __init__(self):
self.__dict__["x"]=1
def __setattr__(self, name, value):
if not self.__dict__.has_key(name):
raise AttriubuteError
else:
self.__dict__[name] = value
def __getattr__(self, name):
try:
return self.__dict__[name]
except KeyError:
raise AttriubuteError
"Daehyok Shin" <sdhyok at email.unc.edu> wrote in message
news:8i9cbh$mev$1 at news2.isis.unc.edu...
> Even though I corrected minor errors, it does not work.
> Refer to the following comments.
> >> class A:
> > > def __init__(self):
> > > self.x = 1 # this code calls __setattr__
> # when I change it into self.__x = 1, it
> raised AttributeError in __setattr__
> > >
> > > def __setattr__(self, name, value):
> > > if name == "x":
> > > self.x = value # this code calls __setattr__
> recursively
> > > else:
> > > raise AttributeError
> > >
> > > def __getattr__(self, name):
> > > if name == "x":
> > > return self.x
> > > else:
> > > raise AttributeError
>
> I found one solution, but expect better one.
>
> -------------- Solution, but not good ------------------
> class A:
> def __init__(self):
> self.__dict__["x"]=1
>
> def __setattr__(self, name, value):
> if not self.__dict__.has_key(name):
> raise AttriubuteError
> else:
> self.__dict__[name] = value
>
> def __getattr__(self, name):
> if not self.__dict__.has_key(name):
> raise AttriubuteError
> else:
> return self.__dict__[name]
>
> "Sean Blakey" <sblakey at freei.net> wrote in message
> news:20000614155102.E16232 at freei.com...
> > 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?)
> >
> > --
> > 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"
> >
>
>
More information about the Python-list
mailing list