Quick question about private/public methods
wurmy at earthlink.net
Thu Nov 15 18:13:31 CET 2001
> 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
I don't know about the implementation issues, but for one thing, this
against the general philosophy of Python, which is usually described as
"consenting adults"... if you want to change attributes, you can do so,
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.
I found that this really was no big deal.
It also goes against rapid prototyping principles. Compare:
x = "bla"
x = "bla"
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
attribute is a lot of extra work, since you need get- and set-methods.
biggie for only one or two attributes, but it becomes a Great Biggie
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
very strict in it. There is the "name mangling" trick with the leading
>>> class Foo:
__x = "hidden"
>>> foo = Foo()
Traceback (most recent call last):
File "<pyshell#4>", line 1, in ?
AttributeError: Foo instance has no attribute '__x'
but you can work around this. There are other ways to do this; there was
"behavior injection" class by Fred Gansevles, which unfortunately didn't
much attention; for a certain application, I hacked up a simple
called "shielded" attributes that you can read at will but certain
apply when you want to set them. I'm sure others have developed their
of private members. And Python 2.2 will offer more ways to do this.
More information about the Python-list