I know python treats this namespace in a different way ever since I found out about
def foo(l=[]):
l.append(1)
print(l)
foo()
foo()
foo([])
foo()
which prints the following.
[1]
[1,1]
[1]
[1,1,1]
So I was sceptical about their use as an object initializers. Then recently I encountered another similarly strange behaviour, demonstrated below.
class Foo:
bar = 0
def __init__(self):
self.a = bar
Foo()
This raises an exception as bar
is not defined inside this namespace.
class Foo:
bar = 0
def __init__(self, a=bar)
self.a = a
Foo()
Now this successfully assigns value held by a class variable foo
to an object a
inside the initializer.
Why do these things happen and how are the default argument values treated?