0

Let's assume I've the following C# class:

public class Test
{
    public double X;
    public double Y;
}

I want to use the above C# Test class from IronPython and as well from CPython (using Pythonnet).

Using IronPython 2.7 I was able to generate an object and initializes the fields using object initialization, see the following Python code:

obj = Test(X = 1.0, Y = 2.0)

See as well the following question Object initialization in IronPython

Using CPython 3.9.7 and Pythonnet 3.01 the above code returns the following error:

TypeError: No method matches given arguments for Test..ctor: ()

As workaround I can use the following Python code:

obj = Test()
obj.X = 1.0
obj.Y = 2.0

But I would like to use object initialization.

1

2 Answers 2

1

Not sure if I get your question, but try this:

Test test = New Test();
/* or */ var test = New Test();
/* then */ test.x = whatever;
2
  • The New keyword and the ; are not needed in Python.
    – Wollmich
    Commented Dec 1, 2022 at 13:27
  • I want to use my C# class from IronPython and CPython (using PYTHONNET).
    – Wollmich
    Commented Dec 1, 2022 at 13:28
0

You can do this in two ways in C#:

  1. Object Initializer approach:
    var obj = new Test { X = 1.0, Y = 2.0 };
    
  2. The constructor approach. For this approach you must add a constructor to the class:
    public class Test
    {
        public double X;
        public double Y;
    
        public Text( double x, double y)
        {
            X = x;
            Y = y;
        }
    }
    
    Then you can create the object with:
    var obj = new Test(1.0, 2.0);
    
4
  • Thanks for your answer. But in my case I don't have the source code of .NET assembly.
    – Wollmich
    Commented Dec 1, 2022 at 13:32
  • 1
    You can derive a class from a C# class in IronPython. This would allow you to add it a constructor (__init__()). Commented Dec 1, 2022 at 13:38
  • But what if the C# class is sealed?
    – Wollmich
    Commented Dec 2, 2022 at 7:25
  • Then write a factory method. Commented Dec 2, 2022 at 13:26

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.