How to Subclass .NET Classes from IronPython

IronPython is awesome. The recent revival of the new IronPython 3 project caused me to look again at IronPython (2.7).

What if you created a base class in .NET and you want to subclass it in your IronPython code?

For my Prototype MonoGame game, I created an AbstractScene class representing a scene. I want to write all the logic for it in Python, which means creating a subclass like CoreGameScene. I want to write Python code like this:

class CoreGameScene(AbstractScene):
    # ... implementation
    # ... calls to super(...)

To get IronPython to understand what AbstractScene is, I need to do two things:

First, I need to tell the runtime to load the types in my .NET assembly. (This forum message from 2009 suggests that this works better than using SetVariable to pass down a specific type.)

That code looks quite simple:

var engine = Python.CreateEngine();

Then, to use it in Python, I just need to fully qualify the class package structure (first line in this code block):

from DeenGames.InfiniteArpg.Scenes import AbstractScene

class CoreGameScene(AbstractScene):
    def __init__(self, graphicsDevice):
        super(CoreGameScene, self).__init__()

Everything works! I can create an instance of CoreGameScene and see the calls to the AbstractScene constructor (which takes a GraphcisDevice parameter).

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Libraries, Wndows Forms and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *