Help with a utility class and having a method call another method from within

Peter Otten __peter__ at web.de
Sat Sep 6 11:30:04 EDT 2003


Ian wrote:

> I have written this utility class that has a method which calls
> another method.  I don't want to pass in the self parameter and was
> wondering by doing this does it make the function to be private or
> uncallable outside of the class.

For new style classes, you can write methods without a self parameter:

class Sample(object):
    def test(arg):
        print arg
    test = staticmethod(test) # this is crucial

    def indirect(self, arg):
        Sample.test("indirect(%s)" % arg)

    def __mangled(self):
        # transformed into _Sample__mangled by the compiler
        pass

    def _privateByConvention(self):
        pass

and then call it with a class or instance:

Sample.test("from class")
instance = Sample()
instance.test("from instance")
instance.indirect("from instance")

In Python, privacy is rather a gentlemen's agreement. You can start a method
name with a single underscore "_" to signal "use at your own risk". 
Two underscores trigger some name mangling by the compiler and can be used
to avoid name clashes. Occasions where this is useful, e. g. to protect a
method against overriding in a subclass, should be rare.

Peter





More information about the Python-list mailing list