Entry
New use for __ names (calling methods only from specific class)
Jul 5th, 2000 10:00
Nathan Wallace, Hans Nowak, Snippet 161, Greg Ewing
"""
Packages: oop;arcane_arts
"""
"""
> 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
###########################################