Wednesday, August 11, 2010

Creating Private Methods in Python

Python, as you may or may not know, is a fully object oriented language and with the newly created ArcPy module for ESRI's ArcGIS Suite, users should start creating programs following some sort of OO design. 
One design pattern to follow is the singleton pattern, which can be found here

Once you have started diving into the world of classes, name spaces, and methods, it's time to figure out how to make methods private.  It's surprisingly simple to do this.  To make something private in python, just put two underscores in front of your method.  That's it, now only that class can access that method. 

Here is a small example:
This class contains two functions.  One that will make the self.foo text upper case, and the other lower case.  The capital method has the two __ in front of the method, and should not be seen by the user, and lower() has no underscores that therefore is public. Using the idle's we can easily show that __capital cannot be used publicly by a user:

Enjoy
A

No comments: