Class Variable Question
Alex Martelli
aleaxit at yahoo.com
Mon Apr 9 11:16:12 EDT 2001
"Robert Johnson" <rjohnson at exotic-eo.com> wrote in message
news:3ad1c7e9$0$196$e2e8da3 at nntp.cts.com...
> I am new to Python and I just read something that I thought was peculiar.
> Is it true that a user can add to the variables of a class just by naming
> the new variable?
Perfectly true, depending on what you mean by "user" (any code
having access to the class-object can do that).
> Like:
>
> ClassObject.var1=5
Yes, or, equivalently, setattr(ClassObject, 'var1', 5).
> Would this create a variable "var1" inside the class even though the
creator
> of the class never intended it to be there (there was no var1 originally)?
Exactly. This is THE way any object's attributes spring into existence,
by the way: they "were not there originally", then they get bound to
something, and, voila -- they now ARE there. Assignment syntax and
getattr are just two handy ways to perform such a binding (there are
others, e.g., def and class statements also bind an attribute in the
namespace in which they are executed).
> If I mistype the variable in my code, a new variable inside the class is
> created rather than flagging the error?
Yep. E.g., if you write:
classObj.variable = 23
classObj.variabile = 2323
there is no way for the compiler to know whether the second
binding is a mistake, or just a perfectly correct new binding
with a name that is very similar to a previous one. Python
doesn't start out ASSUMING all you do is an error...:-).
> Is there a way to prevent this so
> users cannot add variables?
Nope (how would one distinguish 'users' from other pieces
of code for this purpose?). You can wrap objects up into
a Bastion if you have security worries.
> It seems to me that the user could just
> override a class with unrelated data.
Sure, just like he could say x=y-z when actually meaning
x=y+z, and a zillion other horrible programming errors.
Hopefully the user will then run some _tests_ (what other
ways would you suggest for the "plus oops I meant minus"
kind or errors to be caught...?), fix the mistakes he then
finds as a result of his testing, and have code with fewer
errors -- including code free from accidental, erroneous
rebindings of all kinds.
Alex
More information about the Python-list
mailing list