An explanation is given in the answers to this question . To summarize this:
Functions in Python are a kind of object. Because they are a kind of object, they act like objects when instantiated. A function, if defined with a mutable attribute as the default argument, is exactly the same as a class with a static attribute, which is a mutable list.
Lennart Regebro has a good explanation and the answer to Roberto Liffredo's question is excellent.
To adapt Lennart's answer ... if I have a BananaBunch class:
class BananaBunch: bananas = [] def addBanana(self, banana): self.bananas.append(banana) bunch = BananaBunch() >>> bunch <__main__.BananaBunch instance at 0x011A7FA8> >>> bunch.addBanana(1) >>> bunch.bananas [1] >>> for i in range(6): bunch.addBanana("Banana #" + i) >>> for i in range(6): bunch.addBanana("Banana #" + str(i)) >>> bunch.bananas [1, 'Banana #0', 'Banana #1', 'Banana #2', 'Banana #3', 'Banana #4', 'Banana #5'] // And for review ... //If I then add something to the BananaBunch class ... >>> BananaBunch.bananas.append("A mutated banana") //My own bunch is suddenly corrupted. :-) >>> bunch.bananas [1, 'Banana #0', 'Banana #1', 'Banana #2', 'Banana #3', 'Banana #4', 'Banana #5', 'A mutated banana']
How does this relate to features? Functions in Python are objects . This is repeated. Functions in Python are objects .
Therefore, when you create a function, you create an object. When you give a function a mutable default value, you populate this attribute of the object with a mutable value, and each time you call this function, you are working with the same attribute. Therefore, if you use a mutable call (e.g. append), you are modifying the same object as if you were adding bananas to the bunch object.
Sean Vieira Feb 25 '10 at 15:40 2010-02-25 15:40
source share