helper function in a class' namespace



Hi,

the following code works fine

def Helper(M) :
return 'H>'+M

class A(object):
def __init__(self,Msg) :
print Helper(Msg)

B=A('ZZ')

but the Helper function is in the module's namespace.

I'd like to put it into class A's namespace.
Note, the Helper function doesn't need access to any instance attributes.

The first variant

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?)

The alternative

class A(object):
def Helper(M) :
return 'H>'+M
def __init__(self,Msg) :
print A.Helper(Msg)

doesn't work either since now the first argument to A.Helper must be 'A'.

So, isn't it possible to have a helper function in the namespace of a class
without (the overhead of) passing a 'self' or a 'cls' parameter?

Probably I'm hurt by my C++ history.

Many thanks for your help,
Helmut.



--
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
.



Relevant Pages

  • Partial Classes - Aspects
    ... Therefore I implemented some classes Term, Var, Number, Sum, ... def expand: ... will be copyied to the base class Term. ... functions do operate in the wrong global namespace. ...
    (comp.lang.python)
  • Re: Something in the function tutorial confused me.
    ... def f: ... create another place in the namespace of f ... You would instead interpret this similar Python code... ... f which refers to the integer object with the value 5. ...
    (comp.lang.python)
  • Re: func_code vs. string problem
    ... Since 'exec' is able to execute any string or bytecode in the current scope, it would seem possible to execute code of any function in any namespace. ... print abc self.test ... def test: print "ABC" def checkfunction: abc=10 exec myfunction.func_code def checkstring: abc=10 ...
    (comp.lang.python)
  • Re: closures and dynamic binding
    ... inner is located in the code -- where is is compiled. ... def f: ... instead maintains access to the namespace providing x. ... This is the dynamic aspect of closures: ...
    (comp.lang.python)
  • Re: Newcomer question wrt variable scope/namespaces
    ... >>> def foo(): ... Note that there is no error, but the binding affect each function's ... local namespace instead of the global one. ... >>> def blah(): ...
    (comp.lang.python)