[Tutor] Local variable look up outside the function and method

Arup Rakshit ar at zeit.io
Sun May 12 09:04:03 EDT 2019


In the following the function, x is reachable outside the scope of foo function.

In [1]: x = 10

In [2]: def foo():
   ...:     return x
   ...:

In [3]: print(foo())
10

But why it is not the case when the look up happens inside a instance method of a class?

In [1]: class Foo:
   ...:     x = 10
   ...:     def bar(self):
   ...:         return x
   ...:

In [2]: Foo().bar()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-77cc08b8637b> in <module>
----> 1 Foo().bar()

<ipython-input-1-202509464a3d> in bar(self)
      2     x = 10
      3     def bar(self):
----> 4         return x

NameError: name 'x' is not defined

I figured I have to access it like:

In [1]: class Foo:
   ...:     x = 10
   ...:     def bar(self):
   ...:         return self.__class__.x
   ...:
   ...: print(Foo().bar())
10

Just want to know how these search happens in 2 contexts.


Thanks,

Arup Rakshit
ar at zeit.io





More information about the Tutor mailing list