Class Friends

Jeremy Bowers jerf at jerf.org
Fri Aug 27 18:55:28 CEST 2004


On Fri, 27 Aug 2004 15:19:53 +0000, Sean Don wrote:

> 
> Hello!
> 
> Is it possible to make classes friends in Python? Or is it better to just stick
> to "Java style" .isThis, .getThat, .setThis style functions? 
> 
> I understand that classes are generally grouped logically into separate files
> anyway. So, this isn't always necessary. But I'm a perfectionist and was
> wondering if friendships were possible in Python.

In Python, there isn't much of an idea of "Private"; Python's philosophy
is "We're all consenting adults here." Thus, there isn't much of an idea
of "friends" either. In Java terminology, on a technical level everybody
is already friends with everybody else already. 

Ultimately, it is the human meaning of "friendship" that is more
important (classes that twiddle with other classes internals), and Python
allows you to deal with that as you see fit.

In all my years of Python programming, only once have I generated a
"friend" class in the human sense. Generally there are ways around it.

As a final note, don't use 'getThat' or 'setThis'; that's a hack around
Java's weaknesses. Look up "property" in the Python manual and use that;
it is good both for re-factoring classes and for new ones too. This is one
reason that Python "gets away with" the way it works; unless you go out of
your way to break a class's encapsulation, the class author can always
catch things like attribute access with a property.

class MyXActsStrange(object):
    def __init__(self):
        self._x = 0
    def getX(self):
        return self._x + 1
    def setX(self, val):
        self._x = val
    x = property(getX, setX)

>>> a = MyXActsStrange()
>>> a.x
1
>>> a.x = 4 
>>> a.x
5


Very useful.

(Some people would use "self.__x", to get the psuedo-private name munging
invoked. My call is if the "security" isn't perfect there isn't much
point, as the language is already depending on the client programmer to
behave. I think Java can get good security but C++ is already effectively
as permissive as Python, it just makes the hoops harder.)



More information about the Python-list mailing list