简体   繁体   中英

read value from method in a python class in c# using ironpython

I want to read the area method from this python class in c#

Does anybody know what I have to do next to achieve this:

Python class: class Shape(object):

def __init__(self,x, y):

     self.x = x
     self.y = y

def area(self):
    return self.x * self.y

C# code:

        ScriptEngine engine1 = Python.CreateEngine();
        ScriptSource source1 = engine1.CreateScriptSourceFromFile("C:\\C#Projects\\ExcelAddIn\\ExcelAddIn\\Shape.py");
        ScriptScope scope1 = engine1.CreateScope();
        source1.Execute(scope1);

        dynamic class_object1 = scope1.GetVariable("Shape");
        dynamic class_instance1 = class_object1();

You'll have to use the CreateInstance method for this (available here: https://github.com/jdhardy/ironpython/blob/master/Runtime/Microsoft.Scripting/Hosting/ObjectOperations.cs ).

ScriptEngine engine1 = Python.CreateEngine();
ScriptSource source1 = engine1.CreateScriptSourceFromFile("C:\\C#Projects\\ExcelAddIn\\ExcelAddIn\\Shape.py");
ScriptScope scope1 = engine1.CreateScope();
source1.Execute(scope1);

var class_object1 = scope1.GetVariable("Shape");
var class_instance1 = engine1.Operations.CreateInstance(class_object1, 1, 1); // This should create a shape with x = 1 and y = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM