Using Python Classes from .NET

From IronPython Cookbook

Revision as of 19:41, 5 August 2007 by MichaelFoord (Talk | contribs)

Python classes are much more mutable than C# classes, you can add members at runtime and swap out the class of instances or the base classes on the class itself.

This means that you can't treat Python classes as C# classes, but it is still possible use them from C#.

This example uses the IronPython 1.X API.

using System;
using IronPython.Hosting;
using IronPython.Runtime.Types;
using IronPython.Runtime.Operations;

namespace TestPythonConsole
    class Program
        static void Main()
            string code = "import clr\r\nclr.AddReference('TestPythonConsole')\r\nfrom TestPythonConsole import Test\r\nclass X(Test):\r\n     def test(self):\r\n        return 'hello'\r\n\r\n";
            PythonEngine engine = new PythonEngine();
            EngineModule module = engine.CreateModule();
            engine.DefaultModule = module;
            UserType ptype = module.Globals["X"] as UserType;
            Test obj = Ops.Call(ptype) as Test;

    public class Test
        virtual public string test() 
            return "goodbye";


The Python code imports 'Test' (it has to add the right reference to the assembly first). It then subclasses 'Test' in a class called X.

The class we pull out of the Python engine globals is called and the result cast to Test.

Calling the method 'test' calls the subclass rather than the parent class.

Just to make it clearer, the Python code is:

import clr
from TestPythonConsole import Test

class X(Test):
     def test(self):
        return 'hello'

Back to Contents.