Prev: freeze function calls
Next: shelf-like list?
From: Jonas Nilsson on 10 Aug 2010 12:47 On 10 Ago, 13:58, Jonas Nilsson <j...(a)spray.se> wrote: ..... > You stumbled in two python common pitfalls at once :-) > One, the default arguments issue, was already pointed to you. > > The other one is that python variables are just names for objects. > Assigning a variable never mean making a copy, it just means using > another name for the same object. > There used to be a very nice (also graphic) explanationor this > somewhere on the web, but my googling skills failed me this time, > so instead I'll show you the concept using your own code: > >>>> class Family: > ... def __init__(self, fName, members = []): > ... self.fname = fName > ... self.members = members > ... >>>> mlist = ["Bill"] >>>> f1 = Family("Smiths", mlist ) >>>> mlist.append( "John" ) # attempt to not-so-clever reyse of the >>>> sme variable >>>> f2 = Family("Smithers", mlist ) >>>> f1.members > ['Bill', 'John'] > > Now my example is a bit contrieved but I'm sure you got the idea : in > your example is better to copy the list with > self.members = members[:]. > > Better yet, you could make use of python arguments grouping feature : >>>> class Family: > ... def __init__(self, fName, *members ): > ... self.members = list(members) # because members is a > tuple > ... self.fname = fName > ... >>>> f1 = Family("Smith") >>>> f1.members.append("Bill") >>>> f2 = Family("Smithers") >>>> f2.members.append("Joe") >>>> f2.members > ['Joe'] >>>> f1.members > ['Bill'] > > This solves your "no initial member" special case and allows for an > easier syntax for creating class instances > (no brackets involved) > >>>> f3 = Family("Bochicchio", "Angelo", "Francesco", "Mario") >>>> f3.members > ['Angelo', 'Francesco', 'Mario'] >>>> > > > Ciao > ---- > FB Thanks everyone. I was a bit steamed about the problem as it was very unexpected. Because I couldn't figure out what key words to google on, I resorted to posting the problem here. /Jonas
From: Francesco Bochicchio on 10 Aug 2010 14:00
On 10 Ago, 17:57, Stefan Schwarzer <sschwar...(a)sschwarzer.net> wrote: > Hi, > > On 2010-08-10 17:01, Francesco Bochicchio wrote: > > > There used to be a very nice (also graphic) explanationor this > > somewhere on the web, but my googling skills failed me this time, > > so instead I'll show you the concept using your own code: > > Probably this isn't the page you're referring to, but I only > recently gave a beginners' talk at EuroPython: > > http://sschwarzer.com/download/robust_python_programs_europython2010.pdf > > The topic of identity and assignments starts on slide 7, > nice graphics start on slide 10. ;-) > > Stefan Also good :-) But I finally found the page I was referring to: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables Ciao --- FB |