Classes: nested functions vs. private methodes
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Thu May 6 06:02:47 EDT 2010
On Thu, 06 May 2010 11:24:49 +0200, Richard Lamboj wrote:
> Hello,
>
> what should i take:
> - nested functions:
> class MyClass(object)
> def blah(self):
> def blub(var1, var2):
> do something...
> blub(1, 5)
The disadvantage of nested functions is that it is harder to test them in
isolation.
> or
>
> class MyClass(object)
> def blah(self):
> def _blub(var1, var2):
> do something...
> _blub(1, 5)
There is no real point in marking a nested function as "private" with a
leading underscore, as no other object can get access to it.
> - "private" functions:
> class MyClass(object)
> def blah(self):
> self._blub()
> def _blub(self):
> do something...
This has the advantage of allowing you to test blah() and _blub() in
isolation. It has the disadvantage of polluting the namespace of MyClass
with an extra visible method, _blub.
> What is more pythonic?
Both are Pythonic. Private methods are more object oriented, nested
functions are more procedural, but it is mostly a matter of taste which
you use. You can use either, or a combination of both, or even do this:
class _MyClass(object):
"""Private class blah blah blah..."""
def blah(self, arg):
do something...
class MyClass(_MyClass):
"""Public interface to _MyClass"""
def blah(self, arg):
arg = preprocessing(arg)
x = super(MyClass, self).blah(arg)
x = postprocessing(x)
return x
--
Steven
More information about the Python-list
mailing list