Need help with Python scoping rules

Ethan Furman ethan at stoneleaf.us
Fri Aug 28 11:42:26 EDT 2009


kj wrote:
> Miles Kaufmann <milesck at umich.edu> writes:
>>...because the suite  
>>namespace and the class namespace would get out of sync when different  
>>objects were assigned to the class namespace:
> 
> 
>>class C:
>>  x = 1
>>  def foo(self):
>>      print x
>>      print self.x
> 
> 
>>>>>o = C()
>>>>>o.foo()
>>
>>1
>>1
>>
>>>>>o.x = 2
>>>>>o.foo()
>>
>>1
>>2
> 
> 
> But this unfortunate situation is already possible, because one
> can already define
> 
> class C:
>    x = 1
>    def foo(self):
>        print C.x
>        print self.x
> 
> which would lead to exactly the same thing.
> 

This is not the same thing, and definitely not exactly the same thing. 
In your example you are explicitly stating whether you want the original 
class variable, or the current, and possibly different, instance 
variable.  Further, the instance variable will not be different from the 
class variable, even after C.x = whatever, unless the instance has had 
that variable set specifically for it.

In [1]: class C(object):
    ...:     x = 9
    ...:     def doit(self):
    ...:         print C.x
    ...:         print self.x
    ...:

In [2]: test = C()

In [3]: test.doit()
9
9

In [4]: C.x = 10

In [5]: test.doit()
10
10

In [6]: test.x = 7

In [7]: test.doit()
10
7

~Ethan~



More information about the Python-list mailing list