Nice solution wanted: Hide internal interfaces
alex23
wuwei23 at gmail.com
Mon Oct 29 21:37:16 EDT 2012
On Oct 30, 2:33 am, Johannes Bauer <dfnsonfsdu... at 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.
More information about the Python-list
mailing list