How to call python class in c#

In this post, I will show you how to call python class in c#, Create a new python class named Person.py and paste the following code

class  Person:  
def  __init__(self,firstName,lastName,age):  
	self.firstName=firstName  
	self.lastName=lastName  
	self.age=age  
  
def  __str__(self):  
	return  self.firstName  +","+self.lastName+","+self.age  
	def  get_full_name(self):  
	return  "%s,%s"  %  (self.firstName,  self.lastName)  

Open program.cs and add following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Scripting.Hosting;
namespace IronPython_Tut1
{
    class Program
    {
    static void Main(string[] args)
        {
    //Create runtime
            ScriptRuntime runtime = IronPython.Hosting.Python.CreateRuntime();
    //excute 
            ScriptScope scope = runtime.ExecuteFile(@"Person.py");
    //get the Person object
            dynamic Person = scope.GetVariable("Person");
    //Create instanc of Person class.
            dynamic personObject = Person("santosh", "singh", 24);
    //call  the get_full_name method on person instancw
            Console.WriteLine(personObject.get_full_name());
            Console.ReadLine();
        }
    }
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru