Class Variable Question

Steve Holden sholden at holdenweb.com
Mon Apr 9 10:48:17 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?
>
Sure is!

> Like:
>
> 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)?

You've got it.

> If I mistype the variable in my code, a new variable inside the class is
> created rather than flagging the error?  Is there a way to prevent this so
> users cannot add variables?  It seems to me that the user could just
> override a class with unrelated data.
>
That's correct. Python gives you "enough rope to shoot yourself in the
foot", and so does not offer the protection schemes associated with
statically-types languages like Java and C++. This increases the flexibility
of the language, at the (slight) risk of errors which would not occur in
Java or C++.

There is magic you can do to restrict operations of this kind, but most
Python programmers are happy to accept the language as it is, since in
practise this doesn't appear to be a problem.

Look at it this way: you can spend the 60% time saving you will make by
programming in Python to make sure you have not made such errors!

regards
 Steve






More information about the Python-list mailing list