Newbie Q: Class Privacy (or lack of)
Timo
timo.linna at gmail.com
Fri Jul 28 05:51:29 EDT 2006
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'
-- timo
More information about the Python-list
mailing list