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).