Python programmers use some important conventions when writing and implementing classes. Python will understand your code if you don't use them, but humans who have to read your code and figure out what it does will appreciate your using them. Some conventions are as follows:
• Modules that exist mostly to export a single class should be named after the class.
• Class names begin with an uppercase letter. Attribute and method names begin with lowercase letters.
• The name self is used to refer to the name of a class instance.
TECHNICAL A brief privacy note
When you're writing a class attribute, you specify that it is private by naming it with a single leading underscore. Unlike private attributes in modules and packages, however, Python doesn't treat private attributes in classes in any special way. The single leading underscore is just a convention that says to people reading your code, "don't touch this!" (That is, don't try to rewrite it, change it, or use it in any way, or else you might break something.)
Private attributes are most often used in large class hierarchies (but you should use them any time you want to inform users of your class that this is not part of the public interface).
If you name a class attribute with two leading underscores, that tells Python to use name mangling so that base classes and subclasses can't see the attribute (unless they manually do the name mangling themselves). This is an advanced programming tool because it's hard to use with inheritance.
Attributes with two leading and two trailing underscores (like __getattr__ ) aren't private. They are special methods (discussed earlier in this chapter).
Some OOP purists denigrate Python's privacy mechanisms because the privacy mechanisms don't enforce privacy. Pythonistas counter that anyone who really wants to break privacy can do it, and it's more important to document things—and then get on with your work. (In general, Pythonistas say, "Python is a language for consenting adults." That is, Python usually won't prevent you from doing something stupid or complex if you really want to.)
Was this article helpful?