2

我有一个与 C# 中的基类的接口——我希望能够在 IronPython 中实现派生类以实现嵌入式可扩展性。

在 C# 中,我会有类似的东西:

public interface IInterface
{
    bool SomeProperty { get; set; }
    bool SomeMethod(DateTime atTime);
}

public abstract class BaseClass : IInterface
{
    public BaseClass() {}

    private bool someProperty = true;
    public virtual bool SomeProperty
    {
        get { return someProperty; }
        set { someProperty = value; }
    }

    public virtual bool SomeMethod(DateTime atTime)
    {
        return true;
    }
}

然后是控制器类型类

public class SomeOtherClass
{
    List<IInterface> interfaceCollection = new List<IInterface>();

    ... factory here to create C# classes and IPy classes derived from BaseClass or IInterface ...

    interfaceCollection.Add(somePytonDerivedClass);
    foreach (var intExersize in interfaceCollection)
    {
        if (intExersize.SomeProperty == true)
        {
            intExersize.SomeMethod(DateTime.Now);
        }
    }
}

我想在 IronPython 中做一个 impl —— 比如:

class BaseClassIPy (BaseClass):
def __new__(self):
    print("Made it into the class")
    return BaseClass.__new__(self)

def __init__(self):
    pass

def get_SomeProperty(self):
    return BaseClass.SomeProperty

def set_SomeProperty(self, value):
    BaseClass.SomeProperty = value

def SomeMethod(self, atTime):
    return BaseClass.SomeMethod(atTime)

newinit方法被正确调用——

但是当我调用 IPy 类的属性和方法时,调用似乎直接转到基类......

是语法问题吗?即IPy代码是错误的?

还是我完全错过了什么?

问候,乍得

---------------- 编辑 ----- 安装 python 类的方法:

private IInterface GetScriptPlugInNode()
{

    IInterface node = null;

    string plugInScript = "c:\\BaseClassIPy.py";
    string plugInClass = "BaseClassIPy";

    var options = new Dictionary<string, object>();
    ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(options);
    setup.HostType = typeof(SelfContainedScriptHost);  //PAL impl
    setup.DebugMode = true;

    var pyRuntime = new ScriptRuntime(setup);
    var engineInstance = Python.GetEngine(pyRuntime);

    // Redirect search path to use embedded resources
    engineInstance.SetSearchPaths(new[] { String.Empty });

    var scope = engineInstance.CreateScope();

    ScriptSource source = engineInstance.CreateScriptSourceFromFile(plugInScript);

    source.Execute(scope);
    var typeClass = scope.GetVariable(plugInClass);
    var instance = engineInstance.Operations.CreateInstance(typeClass);
    node = instance;

    return node;

}
4

1 回答 1

1

您必须将抽象基类中的接口属性/方法更改为虚拟,以允许 IronPython 类正确继承。

public abstract class BaseClass : IInterface
{
    public BaseClass() {}

    private bool someProperty = true;
    public virtual bool SomeProperty
    {
        get { return someProperty; }
        set { someProperty = value; }
    }

    public virtual bool SomeMethod(DateTime atTime)
    {
        return true;
    }
}
于 2012-05-22T06:28:18.710 回答