Nice solution wanted: Hide internal interfaces

Peter Otten __peter__ at web.de
Mon Oct 29 13:06:30 EDT 2012


Johannes Bauer wrote:

> 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.
> 
> Currently my ugly approach is this: I delare the internal methods
> private (hide from user). Then I have a function which gives me a
> dictionary of callbacks to the private functions of the other objects.
> This is in my opinion pretty ugly (but it works and does what I want).
> 
> I'm pretty damn sure there's a nicer (prettier) solution out there, but
> I can't currently think of it. Do you have any hints?

Maybe you  can wrap A into a class that delegates to A:

>>> class A(object):
...     def __private(self): print "private A"
... 
>>> class Friend(object):
...     def __init__(self, obj):
...             self.__obj = obj
...             self.__prefix = "_%s_" % obj.__class__.__name__
...     def __getattr__(self, name):
...             return getattr(self.__obj, self.__prefix + name)
... 
>>> a = A()
>>> a._A__private() # hard
private A
>>> f = Friend(a)
>>> f._private() # easy
private A

The B instance would refer to A via the Friend instance.




More information about the Python-list mailing list