IronPython - 带有自定义类的"AttributeError:object has no attribute"

McL*_*vin 3 .net c# python ironpython attributeerror

这似乎只是一个我无法弄清楚的简单错误.我在C#WPF应用程序中使用IronPython,并在尝试从自定义C#类运行函数时收到以下错误:AttributeError: 'MyScriptingFunctions' object has no attribute 'Procedure'.

我正在运行的python脚本非常简单,有两行.第1行执行正常,错误发生在第2行.

    txt.Text = "some text"
    MyFunc.Procedure(5)
Run Code Online (Sandbox Code Playgroud)

MyScriptingFunctions.cs:

class MyScriptingFunctions
{
    public MyScriptingFunctions() {}

    public void Procedure(int num)
    {
        Console.WriteLine("Executing procedure " + num); 
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我设置IronPython引擎的方法:

     private void btnRunScript_Click(object sender, RoutedEventArgs e)
     {
        MyScriptingFunctions scriptFuncs = new MyScriptingFunctions();
        ScriptEngine engine = Python.CreateEngine();
        ScriptScope scope = engine.CreateScope();

        ScriptRuntime runtime = engine.Runtime;
        runtime.LoadAssembly(typeof(String).Assembly);
        runtime.LoadAssembly(typeof(Uri).Assembly);

        //Set Variable for the python script to use
        scope.SetVariable("txt", fullReadResultsTextBox);
        scope.SetVariable("MyFunc", scriptFuncs);
        string code = this.scriptTextBox.Text;
        try
        {
            ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);
            source.Execute(scope);
        }
        catch (Exception ex)
        {
            ExceptionOperations eo;
            eo = engine.GetService<ExceptionOperations>();
            string error = eo.FormatException(ex);

            MessageBox.Show(error, "There was an Error");
            return;
        }

    }
Run Code Online (Sandbox Code Playgroud)

我只是设置两个变量:txt哪个是类型System.Windows.Controls.TextBox,MyFunc哪个是我的自定义类的对象MyScriptingFunctions.

我做错了什么,为什么python脚本正确执行TextBox方法而不是我的自定义类的方法?

Jef*_*rdy 6

唯一的想法是我可以看到这可能是一个问题,或者只是一个复制粘贴错误,而MyScriptingFunctions不是public.这应该不是问题,因为你传递了一个实例,而不是尝试导入类,但值得一试.否则一切都很好.

  • 有同样的问题,没有想过让班级公开.对于遇到这个问题的其他人:你的课程不需要公开,但**方法需要公开,以便在大会外看到**.例如,您可以拥有一个实现公共接口的内部类,只要python只调用接口方法即可. (2认同)