helper function in a class' namespace

Arnaud Delobelle arnodel at googlemail.com
Thu Jan 31 17:53:54 EST 2008


On Jan 31, 8:05 pm, Stargaming <stargam... at gmail.com> wrote:
[...]
> > class A(object):
> >    def Helper(M) :
> >      return 'H>'+M
> >    def __init__(self,Msg) :
> >      print Helper(Msg)
>
> > doesn't work since Python is looking for a global function Helper (why?)
>
> Because in the scope of the ``__init__`` function, the name ``Helper`` is
> not bound. It then jumps out to the global scope.

But it is 'Helper' bound in the scope of the *definition* of __init__,
hence you *could* write:

>>> class A(object):
...     def _helper(x): return '<<%s>>' % x
...     def __init__(self, msg, _helper=_helper):
...             print _helper(msg)
...     del _helper
...
>>> A('spam')
<<spam>>
<__main__.A object at 0x70170>

Confusingly yours,

--
Arnaud




More information about the Python-list mailing list