Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > dk.edb.programmering > #46
| From | Bertel Lund Hansen <gadekryds@lundhansen.dk> |
|---|---|
| Newsgroups | dk.edb.programmering |
| Subject | [Python] Call by value eller call by reference? |
| Date | 2016-11-26 13:07 +0100 |
| Organization | A noiseless patient Spider |
| Message-ID | <12v12ak3i5x2k.dlg@lundhansen.dk> (permalink) |
Det her er et lidt hypotetisk problem, for jeg har ikke tænkt mig at benytte mig af mystiske effekter, men jeg faldt over noget i en tutorial som jeg ikke forstod idet jeg altid er gået ud fra at funktioner i Python kun arbejder med en kopi af de overførte parametre. Derfor forstår jeg ikke det følgende eksempel: def changeme_once (mylist): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return def changeme_twice (mylist): "This changes a passed list into this function" mylist = [1,2,3,4]; print "Values inside the function: ", mylist return def changeme_thrice (mylist): "This changes a passed list into this function" mylist = [5,6,7,8]; print "Values inside the function: ", mylist mylist.append([9,10,11,12]); print "Values inside the function: ", mylist return mylist = [10,20,30]; print "Values before change: ", mylist changeme_once(mylist); print "Values outside the function: ", mylist print mylist = [10,20,30]; print "Values before change: ", mylist changeme_twice( mylist ); print "Values outside the function: ", mylist print mylist = [1,2,3,4]; print "Values before change: ", mylist changeme_thrice( mylist ); print "Values outside the function: ", mylist Udskriften ved en kørsel giver: Values before change: [10, 20, 30] Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]] Values before change: [10, 20, 30] Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30] Values before change: [1, 2, 3, 4] Values inside the function: [5, 6, 7, 8] Values inside the function: [5, 6, 7, 8, [9, 10, 11, 12]] Values outside the function: [1, 2, 3, 4] Hvorfor er det kun i changeme_once() at ændringen slår igennem i den ydre variabel? -- Bertel bertel.lundhansen.dk fiduso.dk obese.dk
Back to dk.edb.programmering | Previous | Next | Find similar
[Python] Call by value eller call by reference? Bertel Lund Hansen <gadekryds@lundhansen.dk> - 2016-11-26 13:07 +0100
csiph-web