[Tutor] New Python scoping

Kirby Urner urnerk@qwest.net
Sun, 04 Nov 2001 20:56:11 -0800


    f)  Can someone explain Python scoping rules in general
        for me, taking into account these new changes?

Hi Tommy --

Not entirely sure if I understand your confusions, but the
new scoping rules are more intuitive, what people would
expect, so it's best, if new to Python, to not even remember
the old ways.  If old to Python, forget 'em as well.

However, the scoping rules don't have a lot to do with
classes and objects per se.  What other languages have you
experience with?  Python is simpler than Java in its
approach, is only starting to have something like
abstract classes for example, where you don't need to
instantiate an instance in order to use class methods.

And class variables aren't particularly private.  There's
a way to suggest privacy, but it's not ironclad or anything.

  >>> class A:
  	 def method1(self):
	    print "Howdy!"
	 def __method2(self):
	    print "I'm private!"

	
  >>> a = A()
  >>> dir(a)
  ['_A__method2', '__doc__', '__module__', 'method1']

You see, method2, given the double-underline prefix, has
had its name "mangled" by the interpreter, and is known
internally as _A__method2 -- the class name, and an
underline prefix, have been pre-pended.  So you can't
invoke __method2 directly:

   >>> a.__method2()
   Traceback (most recent call last):
     File "<pyshell#9>", line 1, in ?
       a.__method2()
   AttributeError: A instance has no attribute '__method2'
   >>> a._A__method2()
   I'm private!

Ah, but I *did* invoke it, because I know how the mangling
works, as does any Python programmer.

Really, the private methods and variables technique is
fairly obscure and not used in 99% of Python programs.
Python assumes a collegial environment where people know
what they're doing in a civilized atmosphere.  That context
keeps things simple, straightforward, workaday.

If you're assuming everyone has their heart set on being
malicious and breaking stuff, then you need a more secure
language, like maybe Java.

Kirby

PS:

Note:  even with mangling, you can use the double underline
name as-is *internally* to the class -- which is most
likely, as what's the point of a private method except
to serve some other methods that need it:

  >>> class A:
	 def method1(self):
	    print "Howdy!"
	 def __method2(self):
	    print "I'm private!"
	 def method3(self):
	    self.__method2()

	
  >>> a = A()
  >>> a.method3
  <bound method A.method3 of <__main__.A instance at 0x00D011B0>>
  >>> a.method3()
  I'm private!

Kirby