On Tue, Oct 30, 2012 at 3:33 AM, Johannes Bauer <dfnsonfsdu...@gmx.de> wrote:
> Hi there,
>
> I'm currently looking for a good solution to the following problem: I
> have two classes A and B, which interact with each other and which
> interact with the user. Instances of B are always created by A.
>
> Now I want A to call some private methods of B and vice versa (i.e. what
> C++ "friends" are), but I want to make it hard for the user to call
> these private methods.

The usual convention for private methods is a leading underscore on the name:

class A:
        def foo(self):
                print("Fooing!")
        def _bar(self):
                print("Only my friends may bar me.")

It's only a convention, though; it doesn't make it "hard" to call
them, it just sends the message "this is private, I don't promise that
it'll be stable across versions".

Incidentally, you may want to use a nested class, if the definition of
B is entirely dependent on A. Something like this:

class A:
        class B:
                def _asdf(self,newval=None):
                        if newval is not None: self._val=newval
                        return self._val
                def _qwer(self,parent):
                        parent._bar("My value is: "+self._val)
        def foo(self):
                self.b=self.B()
                self.b._asdf("Hello, world!")
                self.b._qwer(self)
        def _bar(self,msg):
                print("Message from internal: "+msg)

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to