← 输入框|github.com|刷新
Skip to content

Exception when deriving from a .NET class with abstract methods in Python #2571

Open

Description

@Eswcvlad

Environment

  • Python.NET version: 3.0.5
  • Tested on three configurations:
    • Windows 10, Python 3.12.4, .NET Framework
    • Windows 10, Python 3.12.4, .NET 9.0.201
    • Debian 12, Python 3.11.2, .NET 8.0.407

Details

I have an abstract .NET class, which has abstract methods to override within a netstandard2.0 library. When I try to derive from such a class in Python, it throws a TypeError during class object creation.

Below is a basic example.

.NET library code:

namespace TestLib
{
    public abstract class TestClass
    {
        public string Foo()
        {
            return "Foo";
        }

        protected abstract string Bar();
    }
}

Python code:

from pathlib import Path

import clr

clr.AddReference(str(Path(__file__).parent / 'TestLib.dll'))

from TestLib import TestClass


class SubTestClass(TestClass):
    __namespace__ = 'CrlTest'

    def Bar(self):
        return 'Bar'


if __name__ == '__main__':
    stc = SubTestClass()
    print('Foo() -> ' + stc.Foo())
    print('Bar() -> ' + stc.Bar())

Python script output:

Traceback (most recent call last):
  File "<redacted>\crl_test.py", line 10, in <module>
    class SubTestClass(TestClass):
TypeError: Method 'Bar' in type 'CrlTest.SubTestClass' from assembly 'Python.Runtime.Dynamic, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.

Activity

  1. Eswcvlad commented on Apr 3, 2025

    @Eswcvlad
    Author

    After some further testing, it looks like it is specifically the method being protected abstract. If it is public abstract, as with an interface, then it works fine.

  2. Eswcvlad commented on Apr 8, 2025

    @Eswcvlad
    Author

    Looks like this is, actually, a duplicate of #2192, though having protected abstract methods makes the issue more annoying...

    For now I've forked it with a tweak to allow overriding protected methods. The downside is that all protected methods get automatically wrapped into public ones in Python, though, on the other hand, since Python doesn't differentiate between the two, it doesn't seem like a big deal...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions