anonymous
  • anonymous
Strictly python question. Variable names point to objects, they don't contain them - I get that. I am having trouble understanding what is going on with this: def test(a=[]): a.append(1) return a The variable 'a' gets assigned to the same list object each time the function is called, so each time the list object gets mutated. What I don't get is - where is this object? - why does it persist ? - how does python always assign a to the same object? tia
MIT 6.00 Intro Computer Science (OCW)
  • Stacey Warren - Expert brainly.com
Hey! We 've verified this expert answer for you, click below to unlock the details :)
SOLVED
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
chestercat
  • chestercat
I got my questions answered at brainly.com in under 10 minutes. Go to brainly.com now for free help!
anonymous
  • anonymous
You've defined a function test that takes an argument a. If no argument is passed to the function when it is called it will use the default you've specified. In creating the function, you created a list object [ ] for the function to use as its default. The list is part of the function. It persists because there is some other object with a reference to it. In this case the object which is keeping a reference to this list is the function itself. The dir function may help give some insight. It takes an object and returns a list of strings where each string in that list is the name of an attribute of the object. class Foo: def __init__(self,a): self.bar = a f = Foo('stuff') print dir(f) print f.bar The above code shows how dir works. From that info you can take a look at this small example taken from your function test. http://dpaste.com/519173/
anonymous
  • anonymous
Thank you very much for that answer and the dir function. I never even considered that the function was keeping ahold of it and I was going crazy cause it didn't show up in globals() or locals() (from the shell).

Looking for something else?

Not the answer you are looking for? Search for more explanations.