Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why can't variable types be defined by default parameters of python function

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the "python function default parameters can not define variable types", in the daily operation, I believe that many people in the python function default parameters can not define variable types on the question of why there are doubts, Xiaobian consulted all kinds of information, sorted out a simple and easy-to-use method of operation, hope to answer the "python function default parameters why can not define variable types" doubt helpful! Next, please follow the editor to study!

Do not define variable types for the default parameters of the function

You often see a code warning like this:

Default argument value is mutable

It tells us that in the definition of a function, a variable type is used as the default parameter.

Then why is there this warning?

Mutable and immutable types

Mutable type (mutable): list, dictionary

Immutable types (unmutable): numbers, strings, tuples

What's wrong with defining mutable types? Def fun (a = []): a.append (1) print (a) if _ _ name__ = = "_ _ main__": fun () fun () > > [1] [1,1]

You can see that after the default parameter defines a variable type, the default parameter seems to lose its effect when the same function is called for the second or more times.

At this point, in scenarios where you need to call the same function repeatedly, it is very easy to cause a problem, and the problem is not easy to detect. In debug, it will appear that there are no parameters passed in, but the function parameters will have a value and perform operations that should not be performed.

The cause

My understanding:

The function we define is itself an instantiated object of function. Whenever we define a function, we create an instantiated object of function, and the default parameter is its property.

When no parameters are passed in, called as default parameters, and the property value of the function object is changed, the changed property value is saved, and the property value has changed when the same object is called for the second time.

Type (fun) > function solution def fun (a=None): if an is None: a = [] a.append (1) print (a) if _ _ name__ = "_ _ main__": fun () fun () > [1] [1] [1] Note on variable types as default parameters

Please look at the code first to see if the output of the code is what you think it is.

Def e (vPersonl = []): l.append (v) return ll1=e (10) L2yoge (123,[]) L3recoe ("a") print (L1memeL2Personl3) # output: ([10,'a'], [123], [10,'a'])

With regard to the above code, the standard explanation is that expressions with default parameters are evaluated when the function is defined, not when called.

I think the popular explanation is that when the default value is not passed, no matter how many times the function is called, the default "l" is always used inside the function body, and this default "l" is a variable type, so, its change affects all variables pointing to it, that is, L1 and L3.

In order to make the above two points more tenable, I will conduct the following tests.

Test: replace the list of changeable types with the dictionary def e (kjorivrect d = {}): d [k] = v return dd1=e (10pl 10) d2chile (123jue 123c, {}) d3grame ("a", "a") print (d1Magazine d2Magned3) # output: ({'averse:' averse, 10: 10}, {123: 123}, {'await:' averse, 10: 10}) Test: give an immutable type string def e (v) S = ""): s = squarv return ss1=e ("I") s2yoge ("a", "") s3fante ("yes") print (s1mens2mems3) # output: I am

In fact, the above types are already illustrative, but it is not easy to write an article. I decided to use the meta-ancestor package list to see what it would be like to modify the data in this list.

In fact, there is no need to test, the final printed data must be similar to the output of * * "variable type operation" * *.

Why? Because I did not modify Yuanzu itself, what I changed was its variable type list.

You can't go too far, or you'll get a deep copy and a shallow copy.

Test: Yuanzu package a list to def e (vMagne t = ([],)): # remember to use a comma when passing meta-ancestors with elements. T [0] .append (v) # t = t [0] .append (v) to know that t [0] .append (v) does not return a value, t points to None, if so, all external prints are None, so you can't return it this way. # and if you want t [0] = t [0] .append (v) is no good, why? You type dir (()) in ipython and you will know. # well, it's actually because Yuanzu is readable and unwritable. It would be nice if it could slice and traverse. Return tt1=e ("I") T2 roome ("a", ([[],)) T3 roome ("yes") print (T1, "\ n", T2, "\ n", T3) # output: # (['I', 'yes'],) # (['a'],) # (['I', 'yes'],) # ([I', 'yes'],) this ends the study of "why the default parameter of the python function can not define a variable type" I hope I can solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report