Need help with Python scoping rules
Jean-Michel Pichavant
jeanmichel at sequans.com
Tue Aug 25 12:36:28 EDT 2009
kj wrote:
>
> I have many years of programming experience, and a few languages,
> under my belt, but still Python scoping rules remain mysterious to
> me. (In fact, Python's scoping behavior is the main reason I gave
> up several earlier attempts to learn Python.)
>
> Here's a toy example illustrating what I mean. It's a simplification
> of a real-life coding situation, in which I need to initialize a
> "private" class variable by using a recursive helper function.
>
> class Demo(object):
> def fact(n):
> if n < 2:
> return 1
> else:
> return n * fact(n - 1)
>
> _classvar = fact(5)
>
> This code fails to compile, with the error "global name 'fact' not
> defined".
>
[snip]
fact is defined within the Demo class, so to access it, you'll need to
prefix it with Demo:
_classvar = Demo.fact(5).
The problem is, Demo will raise a NameError exception.
The solution is pretty simple, cause your fact function seems to be
unrelated to the Demo class :
def _fact(n):
# some code
class Demo(object):
_classvar = _fact(5)
It may happen that you *want* your fact within the Demo, in you example
it's not that obvious, but I think Java would allow such following patern:
class Color:
def __init__(self, r, g,b):
pass
BLACK = Color(0,0,0)
It make sens from a design point of view to put BLACK in the Color
namespace. But I don't think it's possible with python.
You could trick the system using inheritance:
class Chrome:
def __init__(self, r,g,b)
pass
Putting all your code in the Chrome class then:
class Color(Chrome):
BLACK = Chrome(0,0,0)
I'm not sure this is satisfying.
JM
More information about the Python-list
mailing list