[Tutor] Data hiding in Python.
Don Taylor
nospamformeSVP at gmail.com
Mon Dec 18 17:47:32 CET 2006
I am working my way through 'wxPython in Action' by Noel Rappin and
Robin Dunn and came across this comment about data hiding in their
explanation of the MVC pattern:
".. the View... should never get to see the private internals of the
Model. Admittedly, this is difficult to enforce in Python, but one way
to help enforcement it is to create an abstract Model class that defines
the API that the View can see. Subclasses of the Model can either act
as proxies for an internal class that can be changed, or can simply
contain the internal workings themselves. The first option is more
structured, the second easier to implement."
I like the idea of data hiding but Googling 'Python data hiding' yields
lots of discussion to the effect that it cannot/should not be done.
So what do the authors mean? They do not give any examples of this
technique (at least not so far as I have read in the book) so I have
been trying to figure something out. And then, is it worth the trouble?
Any suggestions? Preferably with code fragments.
Here is what I have got so far:
A calling module:
-caller.py---------------------------------------------------------------------
import model
if __name__ == '__main__':
model.methodA() # test a method call interface
testInstance = model.TestClass() #test a class generation interface
testInstance.methodB() # test a method call within the new class
-------------------------------------------------------------------------------
The actual model module, which does not contain any (or much)
implementation code:
-model.py----------------------------------------------------------------------
import innermodel
__implementation = innermodel.Implementation()
def methodA():
"Example of a method interface."
__implementation.methodA()
def TestClass():
"Example of a class interface."
return __implementation.TestClass()
-------------------------------------------------------------------------------
and then the actual implementation code:
-innermodel.py-----------------------------------------------------------------
class Implementation:
def __init__(self):
print "Implementation initializing..."
def methodA(self):
print "Implementation methodA called."
class TestClass:
def __init__(self):
print "TestClass initializing..."
def methodB(self):
print "TestClass methodB called."
-------------------------------------------------------------------------------
I am not sure if this is what they mean, and if so which is this - a
proxy for an internal class that can be changed, or does it simply
contain the internal workings.
It seems to provide some degree of data hiding, but perhaps too much?
You cannot figure out from the model.py file what are the available
methods for the TestClass class. I guess that these could be documented
in the TestClass docstring.
Don.
More information about the Tutor
mailing list