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 functions
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, wi
On Tuesday 04 December 2012 10:55 AM, Anand Chitipothu wrote:
What is really weird is that the class body is evaluated without
considering the enclosed scope, but the methods defined in the class
have access to the enclosed scope.
Found the culprit. Lets looks at the following code.
code = ""
On 04-Dec-2012, at 10:23 AM, Anand Chitipothu wrote:
> On Tue, Dec 4, 2012 at 10:13 AM, Satyajit Ranjeev
> wrote:
>> 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 is really weird is that the class body is evaluated without
> considering the enclosed scope, but the methods defined in the class
> have access to the enclosed scope.
Found the culprit. Lets looks at the following code.
code = """
x = x+1
def f():
return x
print(x, f())
"""
x = 5
e
On Tue, Dec 4, 2012 at 10:13 AM, Satyajit Ranjeev
wrote:
> 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 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 Tue, Dec 4, 2012 at 9:38 AM, Satyajit Ranjeev
wrote:
> 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
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 yo