Classes: nested functions vs. private methodes
Richard Lamboj
richard.lamboj at bilcom.at
Thu May 6 06:40:16 EDT 2010
Am Thursday 06 May 2010 12:02:47 schrieb Steven D'Aprano:
> 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
Thank you for the nice sample, but what is with multiple inheritance in your
sample? I mean the super call. Why not _MyClass.blah(self, arg). What is when
i have more then one Class from which i inherite and in both are a methode
called "blah", but i just want to call one of them and not both, becouse they
do different things?
Kind Regards,
Richi
More information about the Python-list
mailing list