New use for __ names! (Re: Is there a pattern...)
Greg Ewing
greg.ewing at compaq.com
Thu Sep 2 18:26:16 EDT 1999
"Magnus L. Hetland" wrote:
>
> So I started to wonder - is there an intelligent design pattern that
> addresses this problem, i.e. methods that should only be called from a
> specific class or a specific set of objects or something?
How's this for a sneaky hack which shamelessly misuses
the "__" name mangling mechanism:
class Foo:
def _Blarg__secret(self):
print "secret method called"
class Blarg:
def doit(self, foo):
foo.__secret()
class Impostor:
def doit(self, foo):
foo.__secret()
f = Foo()
b = Blarg()
i = Impostor()
try:
b.doit(f)
i.doit(f)
except AttributeError:
print "impostor detected"
################ Output ###################
secret method called
impostor detected
###########################################
There's-more-than-one-use-for-the-skin-of-a-cat,
Greg
(Somewhat
> like friend classes in C++, I guess - if I don't remember it all
> wrong...)
>
> Of course, you *could* just appeal to the programmers conscience and
> tell him not to call the methods anywhere else, but...
>
> --
>
> Magnus Making no sound / Yet smouldering with passion
> Lie The firefly is still sadder / Than the moaning insect
> Hetland : Minamoto Shigeyuki
More information about the Python-list
mailing list