2012/10/30 alex23 <wuwe...@gmail.com>: > On Oct 30, 2:33 am, Johannes Bauer <dfnsonfsdu...@gmx.de> wrote: >> 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. > > One approach could be to only have the public interface on B, and then > create a wrapper for B that provides the private interface: > > class B: > def public_method(self): > pass > > class B_Private: > def __init__(self, context): > self.context = context > > def private_method(self): > # manipulate self.context > > class A: > def __init__(self): > self.b = B() > self.b_private = B_Private(self.b) > > def foo(self): > # call public method > self.b.public_method() > > # call private method > self.b_private.private_method() > > It doesn't stop a user from accessing the private methods, but it does > separate them so they have to *intentionally* choose to use them. > -- > http://mail.python.org/mailman/listinfo/python-list
Partly unrelated, but you could also define a clear API and expose it through your __init__.py. For example: package/a.py: class A: pass package/b.py: class B:pass package/__init__.py from a import A so now doing "from package import" will only show A. This doesn't work on the method-level, but it's useful to know and commonly done in many projects.. In some projects they even use a file "api.py" to you have to explicitly import from package.api import .. (which I think is overkill since __init__.py does the same) -- http://mail.python.org/mailman/listinfo/python-list