We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

How do I make public and private attributes and methods in my classes?

Python follows the philosophy of we’re all adults here with respect to hiding attributes and methods; i.e. you should trust the other programmers who will use your classes. Use plain attributes whenever possible.

You might be tempted to use getter and setter methods instead of attributes, but the only reason to use getters and setters is so you can change the implementation later if you need to. However, Python 2.2 and later allows you to do this with properties:

http://www.python.org/download/releases/2.2.3/descrintro/#property

If you really must hide an attribute or method, Python does provide a simple form of name mangling. By putting two underscores before the attribute or method name and not putting two underscores after the name, Python will change all uses of the name inside the class by putting the class name in front of it:

class MyClass:
    def public(self):
        pass
    def __private(self):
        # mangled to _MyClass__private
        pass

c = MyClass()
c.public() # this works
c.__private() # this doesn't

You can still call the method using its mangled name, so this feature doesn’t provide much protection.

(Based on a post to comp.lang.python by Steven Bethard)

CATEGORY: tutor