In <[EMAIL PROTECTED]>, Timo wrote: > Steve Jobless kirjoitti: > >> Let's say the class is defined as: >> >> class MyClass: >> def __init__(self): >> pass >> def func(self): >> return 123 >> >> But from the outside of the class my interpreter let me do: >> >> x = MyClass() >> x.instance_var_not_defined_in_the_class = 456 >> >> or even: >> >> x.func = 789 >> >> After "x.func = 789", the function is totally shot. >> > > You can avoid the problem by using the __slots__ definition and > new-style classes (inherit from object): > > class MyClass(object): > > __slots__ = ('bar',) > > def func(self): > return 123 > > x = MyClass() > x.instance_var_not_defined_in_the_class = 456 > ==> > AttributeError: 'MyClass' object has no attribute > 'instance_var_not_defined_in_the_class' > > x.func = 789 > ==> > AttributeError: 'MyClass' object attribute 'func' is read-only > > Only the bar-attribute can be set: > > x.bar = 'foo'
This avoids the problem but you get others in return. And it's an abuse of `__slots__` which is meant as a way to save memory if you need really many objects of that type and not as "protection". Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list