Tools, FAQ, Tutorials:
Function Parameter Default Expression Executed Only Once
Is it true that the function parameter default expression is only executed once in Python?
✍: FYIcenter.com
Yes, the function parameter default expression is only executed once in Python
when the "def" statement is interpreted.
For example, in the following Python code, when the "def profile()" statement is interpreted, the default value for "age" parameter will be set to 18+3 once and stay with that value:
>>> legalAge = 18 >>> def profile(name,age=legalAge+3): ... print("Name: "+name) ... print("Age: "+str(age)) ... >>> profile("Joe") Name: Joe Age: 21 >>> legalAge = 20 >>> profile("Jay") Name: Jay Age: 21
In the following example, the default expression assigned a new "list" object to parameter "x" once. When the function is called multiple times, the same "list" object is referenced again and again.
>>> def growingList(x=[1]): ... x.append(x[len(x)-1]*2) ... return x ... >>> growingList() [1, 2] >>> growingList() [1, 2, 4] >>> growingList() [1, 2, 4, 8] >>> growingList() [1, 2, 4, 8, 16] >>> growingList() [1, 2, 4, 8, 16, 32] >>> growingList() [1, 2, 4, 8, 16, 32, 64]
⇒ Variable Scope in Function Definition Statements
⇐ '*...' and '**...' Wildcard Parameters in Function Definitions
2022-10-26, 1552🔥, 0💬
Popular Posts:
What is EPUB 3.0 Metadata "dc:publisher" and "dc:rights" elements? EPUB 3.0 Metadata "dc:publisher" ...
How to Instantiate Chaincode on BYFN Channel? You can follow this tutorial to Instantiate Chaincode ...
How to use the Atom Online Validator at w3.org? w3.org feed validation service is provided at http:/...
How To Read the Entire File into a Single String in PHP? If you have a file, and you want to read th...
How to run PowerShell Commands in Dockerfile to change Windows Docker images? When building a new Wi...