S
Sandro Dentella
I'd like to understand why += operator raises an error while .append() does
not. My wild guess is the parses treats them differently but I cannot
understand why this depends on scope of the variables (global or class
variables):
a = [0]
class foo(object):
def __init__(self):
print "a: ", a
# += does not work if 'a' is global
#a += [1]
a.append(2)
print "a= ", a
class bar(object):
b = [0]
def __init__(self):
print "b: ", self.b
# += *does* work if 'a' is class var
self.b += [1]
self.b.append(2)
print "b= ", self.b
if __name__ == '__main__':
x = foo()
y = bar()
a: [0]
a= [0, 2]
b: [0]
b= [0, 1, 2]
uncommenting 'a += [1]' would raise:
a:
Traceback (most recent call last):
File "c1.py", line 26, in ?
x = foo()
File "c1.py", line 7, in __init__
print "a: ", a
UnboundLocalError: local variable 'a' referenced before assignment
TIA
sandro
*
not. My wild guess is the parses treats them differently but I cannot
understand why this depends on scope of the variables (global or class
variables):
a = [0]
class foo(object):
def __init__(self):
print "a: ", a
# += does not work if 'a' is global
#a += [1]
a.append(2)
print "a= ", a
class bar(object):
b = [0]
def __init__(self):
print "b: ", self.b
# += *does* work if 'a' is class var
self.b += [1]
self.b.append(2)
print "b= ", self.b
if __name__ == '__main__':
x = foo()
y = bar()
a: [0]
a= [0, 2]
b: [0]
b= [0, 1, 2]
uncommenting 'a += [1]' would raise:
a:
Traceback (most recent call last):
File "c1.py", line 26, in ?
x = foo()
File "c1.py", line 7, in __init__
print "a: ", a
UnboundLocalError: local variable 'a' referenced before assignment
TIA
sandro
*