Thank you Anand for bringing up this thought provoking question!
Regardless of the possible explanations, it has to be said that this
behaviour is indeed confusing. This will conflict with the general idea of
LEGB scoping order (i.e. Local, Enclosing Function local, Global,
Built-in). The
On Tuesday 04 December 2012 09:24 AM, Anand Chitipothu wrote:
Python scoping rules when it comes to classes are so confusing.
Can you guess what would be output of the following program?
x = 1
class Foo:
print(x)
Prints the global x
x = x + 1
print(x)
Prints the local x,
It is the way Python handles objects. Unlike variables in C/C++ where a
variable can point to an address location in the memory Python uses variables
to point to an object.
Now in the first case what you are doing is pointing x to the object 1 in x=1.
When you print x it just prints 1. When
You are right in mentioning scopes.
Lets take case 2:
def f():
x = 1# x is pointing to object 1
class Foo:
print(x) # what you are doing is printing object 1
x = x + 1# you are defining x in the class's scope and pointing
it to the object 2
On 04-Dec-2012, at 10:23 AM, Anand Chitipothu anandol...@gmail.com wrote:
On Tue, Dec 4, 2012 at 10:13 AM, Satyajit Ranjeev
satyajit.ranj...@gmail.com wrote:
You are right in mentioning scopes.
Lets take case 2:
def f():
x = 1# x is pointing to object 1
class Foo: