helper function in a class' namespace

Helmut Jarausch jarausch at skynet.be
Thu Jan 31 14:51:23 EST 2008


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



More information about the Python-list mailing list