IronPython - 自定义类出现“AttributeError: object has no attribute”错误。

4

这似乎只是一个简单的错误,我无法解决。我正在使用IronPython在C# WPF应用程序中运行一个自定义C#类中的函数时,出现以下错误:AttributeError: 'MyScriptingFunctions'对象没有属性'Procedure'

我运行的python脚本非常简单,只有两行。第一行执行正常,错误发生在第二行。

    txt.Text = "some text"
    MyFunc.Procedure(5)

MyScriptingFunctions.cs:

class MyScriptingFunctions
{
    public MyScriptingFunctions() {}

    public void Procedure(int num)
    {
        Console.WriteLine("Executing procedure " + num); 
    }
}

这是我设置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;
        }

    }

我只设置了两个变量:txtSystem.Windows.Controls.TextBox类型的,而MyFunc则是我的自定义类MyScriptingFunctions的对象。

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

1个回答

8

我能看到的唯一可能会出问题,或者只是复制粘贴错误的地方,就是MyScriptingFunctions不是public。这不应该成为问题,因为你正在传递一个实例,而不是尝试导入类,但这也值得一试。否则一切都看起来很好。


3
遇到了同样的问题,没有想到要将类设为公共的。对于其他遇到这个问题的人:你的类不需要是公共的,但是方法需要足够公开以便在程序集外部被看到。例如,你可以有一个内部类来实现一个公共接口,只要 Python 只调用接口方法即可。 - benjamin.popp
我可以确认,刚才遇到了这个问题。谢谢。 - s.m.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接