How to call module functions inside class instance functions?
aleax at mac.com
Sun Aug 19 07:48:32 CEST 2007
beginner <zyzhu2000 at gmail.com> wrote:
> """Test Module"""
> def __module_level_func():
> print "Hello"
> class TestClass:
> def class_level_func(self):
> import testmodule
> The error message I am encountering is: NameError: global name
> '_TestClass__module_level_func' is not defined
> I think it has something to do with the two underscores for
> __module_level_func. Maybe it has something to do with the python
> implementation of the private class level functions.
> By the way, the reason I am naming it __module_level_func() is because
> I'd like __module_level_func() to be private to the module, like the C
> static function. If the interpreter cannot really enforce it, at least
> it is some sort of naming convention for me.
The two underscores are exactly the cause of your problem: as you see in
the error message, the compiled has inserted the CLASS name (not MODULE
name) implicitly there. This "name mangling" is part of Python's rules.
Use a SINGLE leading underscore (NOT double ones) as the "sort of naming
convention" to indicate privacy, and Python will support you (mostly by
social convention, but a little bit technically, too); use a different
convention (particularly one that fights against the language rules;-)
and you're "fighting city hall" to no good purpose and without much hope
of achieving anything whatsoever thereby.
More information about the Python-list