Class Variable Question

David C. Ullrich ullrich at math.okstate.edu
Mon Apr 9 11:53:35 EDT 2001


On Mon, 9 Apr 2001 07:33:24 -0700, "Robert Johnson"
<rjohnson at exotic-eo.com> wrote:

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

Yes.

>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's not entirely clear to me whether you mean to be talking about
setting attributes of classes or attributes of class instances.

If you're talking about class instances, aka objects, you can prevent
unauthorized additions by using a custom __setattr__ method:

class c:
	def __init__(self,x):
		self.x=x
	def __setattr__(self, name, value):
		if name=='x':
			self.__dict__['x']=value
		else:
			raise 'invalid access'

o=c(42)
print o.x
o.x=17
print o.x
o.xx=24
print o.xx

doesn't work, exactly as it shouldn't.

But I don't know how to prevent someone from erroneously adding
xx to the class: If things are as above then

c.xx=24

works. (You might think you could prevent access to o.xx with a
custom __getattr__ method, but that doesn't work because
__getattr__ is not called unless the attribute name is not
found "in the usual places".)

> It seems to me that the user could just
>override a class with unrelated data.
>
>Thanks in advance,
>
>Robert Johnson
>
>




More information about the Python-list mailing list