Nested scopes and class variables

Nick Coghlan ncoghlan at iinet.net.au
Mon Jan 31 06:38:34 EST 2005


wittempj at hotmail.com wrote:
> To me it seems you should do it something like this:
> -def f(x):
> -    class C(object):
> -        def __init__(self, x):
> -            self.x = x # here you set the attribute for class C
> -    c = C(x) # instantiate a C object
> -    print c.x
> 
> -f(5)
> 

That does something different - in this case, x is an instance variable, not a 
class variable.

You do raise an interesting questions though:

Py> def f(x):
...   class C(object):
...     x = None
...     def __init__(self):
...       if C.x is None:
...         C.x = x
...   C()
...   print C.x
...
Py> x = 5
Py> f(6)
6

So, the real problem here is the interaction between the ability to write 
"<name> = <name>" in a class definition with the reference on the RHS being 
resolved in the global namespace and nested scopes (since that first lookup does 
NOT respect nested scopes).

Functions don't have the problem, since they don't allow that initial lookup to 
be made from the outer scope.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list