IronPython for C#(三)
如何在C#代码中实例化一个python的类???
IronPython类不是.NET类。它们是IronPython.Runtime.Types.PythonType的实例,它是Python元类。这是因为Python类是动态的,并且支持在运行时添加和删除方法,这是.NET类无法做到的。
class MyClass:
i = 123
__name = "NB"
def __init__(self, num):
self.i = num
def h(self):
return "Hello"
using System;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using IronPython.Runtime.Types;
public class Program
{
static void Main(string[] args)
{
ScriptRuntime pyRuntime = Python.CreateRuntime();
dynamic scope = pyRuntime.UseFile("test.py");
//返回类型是OldClass,利用dynamic方便调用
dynamic oldClass = scope.MyClass;
//返回类型是OldInstance
dynamic oldInstance = scope.MyClass(56); //带参数的构造函数
dynamic res = oldInstance.h();
dynamic i = oldInstance.i;
//dynamic name = oldInstance.__name; //私有变量不能访问
}
}
类似于反射的代码如下:
static void Main(string[] args)
{
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("test.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
dynamic myclass = scope.GetVariable("MyClass");
dynamic cla = myclass(36);
dynamic res = cla.h();
dynamic i = cla.i;
}
ObjectOperations提供了大量的对象操作,比如成员访问、转换、索引和加法之类的东西。有几个自省和工具支持服务,可用于更高级的主机。你得到ObjectOperation实例,它们被绑定到它们的语义引擎上的操作。您可以共享ObjectOperations的默认实例引擎的所有用途。但是,非常高级的主机可以创建新的实例。
static void Main(string[] args)
{
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("test.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
ObjectOperations op = engine.Operations;
dynamic myclass = scope.GetVariable("MyClass");
dynamic instance = op.CreateInstance(myclass, 65);
dynamic result = op.InvokeMember(instance, "h");
}