Newbie Q: Class Privacy (or lack of)
Antoon Pardon
apardon at forel.vub.ac.be
Wed Aug 2 11:53:53 EDT 2006
On 2006-07-28, Marc 'BlackJack' Rintsch <bj_666 at gmx.net> wrote:
>>
>> 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".
I find that a strange purpose because when you are working on a class,
you don't necessarily know if you will ever know many instance of that
class. So should I use __slots__ in all my classes, just to be sure
for when someone wants many instances of one?
--
Antoon Pardon
More information about the Python-list
mailing list