Newbie Q: Class Privacy (or lack of)

Jean-Paul Calderone exarkun at divmod.com
Mon Jul 24 23:12:52 EDT 2006


On Tue, 25 Jul 2006 02:49:06 GMT, Steve Jobless <sjobless at rotten.apple.commie> wrote:
>Hi,
>
>I just started learning Python. I went through most of the tutorial at
>python.org. But I noticed something weird. I'm not talking about the
>__private hack.
>
>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.
>
>Are these bugs or features? If they are features, don't they create
>problems as the project gets larger?

If you do things like this, you will probably encounter problems, yes.

Fortunately the solution is simple: don't do things like this ;)

It is allowed at all because, to the runtime, "x.someattr = someval" is
no different from "self.someattr = someval".  The fact that a different
name is bound to a particular object doesn't matter.

Jean-Paul



More information about the Python-list mailing list