python语言for循环中用字典保存lambda函数时为什么只保存最后一个lambda方法呢?
我尝试写了个类,代码如下
import osimport sysimport stringclass MyOs: def __init__(self,osType='win32',logger=sys.stdout): self.logger=logger self.osType=osType if osType=='win32': self.seperator='\\' else: self.seperator='/' def setFunc(self): selfClass=self.__class__ funcList={'mkdir':selfClass.getMkdirCmd, 'copy':selfClass.getCopyCmd, 'move':selfClass.getMoveCmd, 'delete':selfClass.getDelCmd} for funcName,function in funcList.items(): print funcName,"==",function selfClass.__dict__[funcName]= lambda *argv: self.executeCmd(function(*argv)) def executeCmd(self,cmd): os.system(cmd) self.logger.write(cmd+'\n') def getCopyCmd(self,src,des): if self.osType=='win32': cmd="copy "+src+" "+des else: cmd="mv "+src+" "+des return cmd def getMoveCmd(self,src,des): if self.osType=='win32': cmd="move "+src+" "+des else: cmd="mv "+src+" "+des return cmd def getDelCmd(self,fileName): if self.osType=='win32': cmd='del '+fileName else: cmd='rm -rf '+fileName return cmd def getMkdirCmd(self,dirName): if self.osType=='win32': cmd='mkdir '+dirName else: cmd='mkdir -p '+dirName return cmdif __name__=='__main__': myOs=MyOs('win32') myOs.setFunc() myOs.mkdir(r'c:\test')#代码完结
def setFunc(self): selfClass=self.__class__ funcList={'mkdir':selfClass.getMkdirCmd, 'copy':selfClass.getCopyCmd, 'move':selfClass.getMoveCmd, 'delete':selfClass.getDelCmd} for funcName,function in funcList.items(): print funcName,"==",function selfClass.__dict__[funcName]= lambda *argv: self.executeCmd(function(*argv))
def wrapper(func): def f(*args): self.executeCmd(func(*args)) return f