About classes and OOP in Python

Sion Arrowsmith siona at chiark.greenend.org.uk
Mon Apr 10 12:01:28 EDT 2006


fyhuang <fyhuang at gmail.com> wrote:
> [ ... ] no such thing as a private variable. Any
>part of the code is allowed access to any variable in any class, and
>even non-existant variables can be accessed: they are simply created.

You're confusing two issues: encapsulation and dynamic name binding.
You might also want to check out the difference between read and
write access to non-existant variables.

>I'm wondering what the philosophy behind this is,

"We are all consenting adults." And probably experience of data
encapsulation being more of a hinderence than a benefit.

> and if this
>behaviour is going to change in any future release of Python.

I damn well hope not.

And if you want to control those writes, try this for a base class:

class restrict_set:
    def __init__(self, allowed_names):
        self._allowed_names = set(allowed_names)
    def __setattr__(self, name, value):
        if not name.startswith('_') and name not in self._allowed_names:
            getattr(self, name)
        self.__dict__[name] = value

(Someone else can do the new style class and the metaclass versions.)

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |    -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list