[IronPython] .NET constructors

Jonathan Jacobs korpse-ironpython at kaydash.za.net
Mon Jun 19 02:07:42 PDT 2006


Hi,

(I didn't see any of these things on the CodePlex issue tracker, sorry if 
these are old news.)

Trying to define a class that derives from my .NET object, with a single 
constructor that takes more than 4 arguments, explodes:

Test.cs:
public class Test {
     public Test(int a, int b, int c, int d, int e) {
     }
}

 >>> class PyTest(Test): pass
...
Traceback (most recent call last):
   File , line 0, in <stdin>##22
SystemError: too many args

Adding a second constructor that takes fewer than 5 arguments lets me at least 
define my class, however I get some odd behaviour from the 5-argument 
constructor (the 2-arg constructor works fine):

Test.cs:
public class Test {
     public Test(int a, int b) {
     }
     public Test(int a, int b, int c, int d, int e) {
     }
}

 >>> class PyTest(Test): pass
...
 >>> PyTest(1, 2)
<PyTest object at 0x000000000000002C>
 >>> PyTest(1, 2, 3, 4, 5)
Traceback (most recent call last):
   File , line 0, in <stdin>##35
TypeError: PyTest() takes at most 6 arguments (6 given)

Adding an initialiser to my derived class doesn't behave properly:

 >>> class PyTest(Test):
...   def __init__(self, a):
...     print 'XXX'
...     Test.__init__(self, a, 2)
...
 >>> PyTest(1) # try __init__
Traceback (most recent call last):
   File , line 0, in <stdin>##51
TypeError: PyTest() takes at least 3 arguments (2 given)
 >>> PyTest(1, 2) # see if base object's constructor still exists then
Traceback (most recent call last):
   File , line 0, in <stdin>##52
TypeError: __init__() takes exactly 2 arguments (3 given)

And finally, adding a kwarg gets us some more quirky behaviour:

 >>> class PyTest(Test):
...   def __init__(self, a, b=2):
...     print 'XXX'
...     Test.__init__(self, a, b)
...
 >>> PyTest(1)
Traceback (most recent call last):
   File , line 0, in <stdin>##67
TypeError: PyTest() takes at least 3 arguments (2 given)
 >>> PyTest(1, 2)
XXX
<PyTest object at 0x0000000000000031>

Regards
-- 
Jonathan

When you meet a master swordsman,
show him your sword.
When you meet a man who is not a poet,
do not show him your poem.
                 -- Rinzai, ninth century Zen master


More information about the users mailing list