What is the scope of a defaulted parameter in Python?

前端 未结 7 1522
攒了一身酷
攒了一身酷 2020-12-13 04:34

When you define a function in Python with an array parameter, what is the scope of that parameter?

This example is taken from the Python tutorial:

de         


        
7条回答
  •  有刺的猬
    2020-12-13 04:55

    The explaination is given in answers to this question. To sum it up here:

    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 a default argument, is exactly the same as a class with a static attribute that is a mutable list.

    Lennart Regebro has a good explanation and the answer to the question by Roberto Liffredo 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 apply to functions? Functions in Python are objects. This bears repeating. Functions in Python are objects.

    So when you create a function, you are creating an object. When you give a function a mutable default value, you are populating that object's attribute with a mutable value, and every time you call that function you are operating on the same attribute. So if you are using a mutable call (like append), then you are modifying the same object, just as if you were adding bananas to the bunch object.

提交回复
热议问题