程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The wonderful use of Python list as the default parameter of function

編輯:Python

We know Python The default parameter value of the function has been generated when defining the function , If it's a mutable object , The same object from beginning to end , So the changes will be saved , The default parameter of the next call is the modified , Instead of the one seen in the parameter list . Reference resources :Python The default parameter value of the function has been generated when defining the function

This is a pit , But if you make good use of it, it can be very convenient .

There's a need today : Avoid calling external methods to create objects repeatedly every time the class is initialized , You want to create it at most once , Then use this object . It's like this :

WORD = 123
class Test():
def __init__(self, Trans):
self.wd = Trans(WORD)

Trans Is an external method , need Test When the class is initialized, it is passed .( If not, I could have created global variables outside the class TRANS_WORD=Trans(WORD),self.wd=TRANS_WORD You can create it only once )

establish Trans(WORD) More time-consuming , So I hope to use this after creating it once . Using closures is certainly one way , But relatively cumbersome , So I thought of using the default parameters :

WORD = 123
class Test():
def __init__(self, Trans, trans_list=[]):
if not trans_list:
trans_list.append(Trans(WORD))# Note that this must be modified in situ ,+=、extend It's OK ,= You can't 
self.wd = trans_list[0]

Then create this class many times ,trans_list Can not pass , Only for the first time Trans(WORD), After that, the same one created for the first time is used Trans(WORD).


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved