This is an old copy of the Python FAQ. The information here may be outdated.

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:

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):
    def __private(self):
        # mangled to _MyClass__private

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)



A Django site. rendered by a django application. hosted by webfaction.