Coming from a C++ / C# background, the lack of emphasis on private data
seems weird to me. I've often found wrapping private data useful to
prevent bugs and enforce error checking..
It appears to me (perhaps wrongly) that Python prefers to leave class
data public. What is the logic behind that choice?
Python presumes the programmer knows what they want to do...
Common convention is to use a leading _ to signify attributes that
are "internal details, touch at your own risk".
__ (two leading underscores) results in name-mangling. This /may/ be
used to specify "private" data, but is really more useful when one is
designing with multiple super classes:
class X(A, B, C):
...
If, say, A and C both have an attribute "m" (or "_m", instances of X
would have only a single common "m"/"_m". Using "__m" in each of A and C
will result in instances of X having two attributes -- name mangled to
refer to the original parent class.
.... def __init__(self):
.... super(A, self).__init__()
.... self.m = "I'm Come From A"
.... self.__n = "I'm from A"
.... print "Init A, m is", self.m
.... .... def __init__(self):
.... super(B, self).__init__()
.... self.m = "I'm From B"
.... self.__n = "I come from B"
.... print "Init B, m is", self.m
.... .... def __init__(self):
.... super(X, self).__init__()
.... self.__n = "And I'm in X"
.... Init B, m is I'm From B
Init A, m is I'm Come From A['_A__n', '_B__n', '_X__n', '__class__', '__delattr__', '__dict__',
'__doc__', '__getattribute__', '__hash__', '__init__', '__module__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__str__', '__weakref__', 'm']
Note how there is only ONE "m", but three "__n"s (_A, _B, and _X
variants).
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/