Beginner's scoping question
Ivo Woltring
Python at IvoNet.nl
Thu Nov 11 12:59:42 EST 2004
On 10 Nov 2004 12:40:34 -0800, contact at alanlittle.org (Alan Little)
wrote:
>a=1
>b=[]
>class C():
is should be...
class C: # whithout the ()
> def __init__(self):
> a=2
> b.append(3)
>
>c = C()
>
>print b
># [3]
>
># but ...
>print a
># 1
>
>???
a=1
b=[]
class C:
def __init__(self):
global a # !!!!!!!!!!!
a=2
b.append(3)
c = C()
print b
# [3]
# but ...
print a
# 2
a in the class is a local to that class and because it in not assiged
to self.a it is also not normally addressable outside the class
if you want to change the already existing global a you have to
declare it global (see code)
You try to append to a non-existing local variable b.
Python first tries the local() namespace and then the global()
it finds b in the global namespace and appends the value.
cheerz,
Ivo
More information about the Python-list
mailing list