可悲的我一直以为copy模块是用C写的,有时候需要深入了解deepcopy,文档描述的实在太简单,还是不知所云。
比如说最近看sqlmap源码中AttribDict的_deepcopy__有些疑惑,
def __deepcopy__(self, memo):
retVal = self.__class__()
memo[id(self)] = retVal
for attr in dir(self):
if not attr.startswith('_'):
value = getattr(self, attr)
if not isinstance(value, (types.BuiltinFunctionType, types.BuiltinFunctionType, types.FunctionType, types.MethodType)):
setattr(retVal, attr, copy.deepcopy(value, memo))
for key, value in self.items():
retVal.__setitem__(key, copy.deepcopy(value, memo))
return retVal
这个memo是啥玩意,为啥要id(self),如果是统一都是id,直接传个self,copy内部做id的操作不是更简单。
第二个问题我们自己思考一下就可以解决,用id肯定是为了唯一识别,如果把self传过去,很危险。因为你压根不知道内部将对self做什么操作,也许你会疑惑是否对self本身有危害吗?这也符合传递参数最