On 10-jan-2006, at 13:02, Perdaen, D.M.L. wrote:

> I am a novice in python and I did some observations that resulted  
> in two questions:
You can speak dutch here :-)

>
> Question 1: Why is it that the dictionary 'b' is global over the  
> methods in scrips 1a and 1c and the result of 'print b' is { 'z' :  
> 10 }? I would expect that dictionary 'b' would be created locally  
> in 'subtest' and that it would stay empty in 'def test' just like  
> in 'script 1b'. Can anybody explain the differences?

You really should read the tutorial. In script 1a test creates a new  
dictionary and passes a reference to that dictionary to subtest.  
Subtest then modifies that dictionary, it would also do that if you  
defined subtest as like so: def subtest(c): c['z'] = 10. In script 1b  
you create two dictionaries, one in test and one in subtest.  In  
script 1c subtest creates a second reference to the same dictionary  
'a = b' does not copy the dictionary but binds the name 'a' to the  
same object as 'b' is bound to.

Ronald

> # 1a
> def test():
>     b = {}
>     subtest(b)
>     print b
> def subtest(b):
>     b['z'] = 10
>
> p = test()
>
> result: b = { 'z' : 10 }
>
> # 1b
> def test():
>     b = {}
>     subtest(b)
>     print b
> def subtest(b):
>     b = {}
>     b['z'] = 10
>
> p = test()
>
> result: b = {}
>
> # 1c
> def test():
>     b = {}
>     subtest(b)
>     print b
> def subtest(b):
>     a = b
>     a['z'] = 10
>
> p = test()
>
> result: b = { 'z' : 10 }
>
> Question 2: In script 2a list 'b' stays the same as list 'a'. In  
> scrips 2b int 'b' doesn't stay as int 'a'. Can anybody explain  
> these differences?
>
> # 2a
> a = [ 1, 2, 3 ]
> print a
> b = a
> print b
> print a.pop()
> print a
> print b
>
> result:
> [ 1, 2, 3 ]
> [ 1, 2, 3 ]
> 3
> [ 1, 2 ]
> [ 1, 2 ]
>
> # 2b
> a = 1
> print a
> b = a
> print b
> a += 1
> print a
> print b
>
> result:
> 1
> 1
> 2
> 1
> _______________________________________________
> Python-nl mailing list
> Python-nl@python.org
> http://mail.python.org/mailman/listinfo/python-nl

_______________________________________________
Python-nl mailing list
Python-nl@python.org
http://mail.python.org/mailman/listinfo/python-nl

Antwoord per e-mail aan