Quick question about private/public methods

Hans Nowak wurmy at earthlink.net
Thu Nov 15 18:13:31 CET 2001


modman wrote:
> 
> Why does python not provide for this? it can not possibly hurt any
> functionality can it? I sort of like the public/private Idea cause it
> hides the actual methods from the person using the class and the person
> only needs to know a few little things about what they can pass to the
> method it also makes the implementation of a class easier to understand
> when public methods like getEggType() and spamType() are used.
> 
> just wondering cause I was messing with Python just before I started
> into C++ at school and I thought that the public/private Idea was pretty
> cool.

I don't know about the implementation issues, but for one thing, this
goes
against the general philosophy of Python, which is usually described as
"consenting adults"... if you want to change attributes, you can do so,
and
Python doesn't stop you. 

When I first got to know Python, I knew (some) C++ and Delphi, and the 
absence of private members was greatly disconcerting to me-- at first.
Later
I found that this really was no big deal.

It also goes against rapid prototyping principles. Compare:

class Foo:
    x = "bla"

and (pseudo-Python):

class Foo:
    private: 
        x = "bla"
    public:
        def get_x(self):
            return self.x
        def set_x(self, s):
            assert type(s) == type("")
            self.x = s
    
Adding an attribute to a class is one thing, but having a private or
protected
attribute is a lot of extra work, since you need get- and set-methods.
No
biggie for only one or two attributes, but it becomes a Great Biggie
(TM) when
you have 10 of them or so. The prototyping becomes much less rapid. :-)

Then again, Python does have ways to emulate private members... it's
just not
very strict in it. There is the "name mangling" trick with the leading
double
underscore:

>>> class Foo:
	__x = "hidden"
	
>>> foo = Foo()
>>> foo.__x
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in ?
    foo.__x
AttributeError: Foo instance has no attribute '__x'
>>> 

but you can work around this. There are other ways to do this; there was
the
"behavior injection" class by Fred Gansevles, which unfortunately didn't
get 
much attention; for a certain application, I hacked up a simple
framework myself,
called "shielded" attributes that you can read at will but certain
restrictions
apply when you want to set them. I'm sure others have developed their
own flavors
of private members. And Python 2.2 will offer more ways to do this.

HTH,

--Hans



More information about the Python-list mailing list