Message208312
Perhaps a 3rd FAQ something like this?:
Why is changing a list in one instance of a class also changing it in another instance of the same class?
This happens:
>>> class A(object):
... def __init__(self, fruit=[]):
... self.fruit = fruit
...
>>> an_A = A()
>>> an_A.fruit.append('apple')
>>> another_A = A()
>>> print another_A.fruit
['apple']
>>> another_A.fruit.append('banana')
>>> print another_A.fruit
['apple', 'banana']
>>> print an_A.fruit
['apple', 'banana']
>>> print an_A.fruit is another_A.fruit
True
>>> print an_A.fruit is A().fruit
True
because of a combination of the above two FAQs, first the default argument is evaluated when the 'def' statement is executed and creates an instance of list. After that new instances of A have a variable 'fruit' that is the name for that instance of list.
I'm not sure whether I should be using as general terms as possible for the Q, i.e. 'mutable object' instead of 'list'. I'll reread http://docs.python.org/devguide/documenting.html and the FAQs before writing the patch. |
|
Date |
User |
Action |
Args |
2014-01-16 21:09:24 | Fran.Bull | set | recipients:
+ Fran.Bull, r.david.murray, docs@python, m123orning |
2014-01-16 21:09:24 | Fran.Bull | set | messageid: <1389906564.87.0.386392793936.issue20135@psf.upfronthosting.co.za> |
2014-01-16 21:09:24 | Fran.Bull | link | issue20135 messages |
2014-01-16 21:09:24 | Fran.Bull | create | |
|