[Tutor] declaring private attributes...
Tue Apr 29 06:25:06 2003
At 10:14 2003-04-29 +0200, Kristoffer Erlandsson wrote:
>On Wed, Apr 30, 2003 at 02:06:49AM +0800, x wrote:
> > is there a way for me to declare private, protected or static class
> attributes (like java)???
>Private, yes (sort of). See
>for more info.
>You can not create protected attributes in Python. Everything is public or
But people often use a single underscore to denote protected, like this:
This is not enforced by python, but you can easily write a code scanner
that will warn you if an attribute which starts with a single underscore
is preceeded by something other than "self". That would probably find
almost all violations. Another option is to have that "code scanner" in
your head... But there is no consensus among python programmers to do
If I remember correctly, "from x import *" won't import anything that
starts with _, so there is some kind of underlying support for the
notion of _ as protected or internal also in the implementation. It
is common that modules intended purely for internal use in a package
have names that start with _, such as _sqlite and sqlite, where you
import sqlite and program against that, and _sqlite is a shared object
(or dll) which is used by sqlite to implement the database.
Python is a high level language, and it doesn't provide access to low
level manipulation like C and C++ does, but other than that, the python
approach is more to make it easy to do the right thing, than to make it
difficult to do bad things. In general, it's up to the programmer to make
a program correct and maintainable, but it's good if the language doesn't
encourage bad coding. On the other hand, it's good if it doesn't make it
too difficult to "cheat" when you have to do that. Putting up artificial
hinders will often lead to even worse code than the one it was supposed to
Magnus Lycka (It's really Lyckå), email@example.com
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program