[Tutor] New Python scoping
alan.gauld@bt.com
alan.gauld@bt.com
Mon, 5 Nov 2001 11:03:42 -0000
> One of the reasons I haven't really used Python a lot in the
> past is because of the difficulty in creating enforced
> capsulation of both variables and methods in
> Python objects.
Encapsulation means keeping them together as a single
entity - an object. Python does that just fine.
Some people in recent years have started to declare
that encapsulation should also mean making data
members inaccessible from outside the object except
through function members(aka methods). This is
frankly bizarre but several OO languages do it.
Python provides limited support for this with
the _name syntax.
This is really part of Information Hiding, a useful
but unrelated charateristic to data/method encapsulation.
> Forgive me for not really understanding what the philosophy
> behind this paradigm
If you don't understand the paradigm why is it an issue?
> the new scoping rules for the latest version of
> Python change this in any way.
I don't think the scoping rules affect the name
visibility rules in any way. But I'm open to correction.
> So my questions are thus--
> a) what ways can one create encapsulated, private
> routines and/or variables in a Python object...
Encapsulated methods are the normal Python class
definition syntax.
Private methods use a naming convention - single
underscore I think? I never use it...
> b) Is such a thing really even necessary?
Encapsulation is for OO - its almost the definition of
an Object! Visibility controls are sometimes nice to have
but not necessary - Lisp, Delphi, Python and many other
OO languages don't put a lot of stress on this..
> c) Wouldn't namespace conflicts arise?
Only if you try to use the same name for different things
within a class hierarchy. Bad practice anyway. Otherwise
all class names are contained within the class scope so
there is no conflict.
> to make a new object every time you need a new
> namespace?
No, but a new object does create a new namespace. But
modules have a namespace and indeed classes themselves
provide a namespace similar to C++/Java's static feature.
> d) Has a new reasoning been adopted within the Python
> community about scoping issues? Is this the driving
> factor behind the changes?
No. I don't think so.
> e) Do Python's new scoping rules change the design
> paradigm and coding methodologies for OO
> programming in Python? If yes, how so?
OO programming is almost language independant.
There are issues in the detail around dynamic vv static
typing etc. The latter makes design much more constrained
and usually requires many more classes. But the design
paradigm of creating abstract frameworks of classes
and then providing concrete implementations of those
remains constant. A good book on this is Robert Martin's
OOD book.
> f) Can someone explain Python scoping rules in general
> for me, taking into account these new changes?
I'll leave that to somebody else :-)
Alan G.