IronPython - "AttributeError: object has no attribute&q

本文关键字:has no attribute object AttributeError quot IronPython | 更新日期: 2023-09-27 18:18:59

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

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

    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;
        }
    }

我只是设置了两个变量:txt 类型为 System.Windows.Controls.TextBoxMyFunc 是我的自定义类 MyScriptingFunctions 的对象。

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

IronPython - "AttributeError: object has no attribute&q

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