希望这个答案对正在研究这个老问题的人有所帮助。
查看 IronPython 2.7.7 的源代码,特别是来自的 builtin.cs 文件
https://github.com/IronLanguages/main/blob/3d9c336e1b6f0a86914a89ece171a22f48b0cc6e/Languages/IronPython/IronPython/Modules/Builtin.cs
可以看到,2参数函数调用5参数重载时使用默认值。
public static object __import__(CodeContext/*!*/ context, string name) {
return __import__(context, name, null, null, null, -1);
}
为了复制这一点,我使用了具有类似默认值的委托。
delegate object ImportDelegate(CodeContext context, string moduleName, object globals = null, object locals = null, object fromlist = null, int level = -1);
protected object ImportOverride(CodeContext context, string moduleName, object globals = null, object locals = null, object fromlist = null, int level = -1)
{
// do custom import logic here
return IronPython.Modules.Builtin.__import__(context, moduleName, globals, locals, fromlist, level);
}
覆盖内置导入函数如下所示
private ScriptEngine pyengine;
private ScriptingEngine()
{
Dictionary<string, object> options = new Dictionary<string, object>();
options["Debug"] = true;
pyengine = Python.CreateEngine(options);
var builtinscope = Python.GetBuiltinModule(pyengine);
builtinscope.SetVariable("__import__", new ImportDelegate(ImportOverride));
}