[IronPython] Constructors & inheriting from standard .NET classes

Michael Foord fuzzyman at voidspace.org.uk
Sat Aug 22 01:42:57 CEST 2009


Zach Crowell wrote:
>
> I am unable to inherit from .NET classes which do not define a 
> parameterless constructor.  Is this expected behavior? Is there 
> another way to make this inheritance work?
>
>  
>
> Here's a simple case.
>
>  
>
> using System;
>
>  
>
> namespace Test
>
> {
>
>     public class Base
>
>     {
>
>         public Base(int i)
>
>         {
>
>         }
>
>     }
>
> }
>
>  
>
> *import *clr
>
> clr.*AddReference*('Test')
>
> *import *Test
>
>  
>
> *class **Derived*(Test.Base):
>
>     *def **__init__*(self):
>
>         pass
>
>  
>
> d = *Derived*()
>
>  
>
> Traceback (most recent call last):
>
>   File "d:\tmp\class.py", line 9, in d:\tmp\class.py
>
> TypeError: Derived() takes exactly 2 arguments (1 given)
>

When you inherit from a .NET type and wish to provide an alternate 
constructor you need to override __new__ instead of or as well as __init__.

*class **Derived*(Test.Base):

       def __new__(cls):
          return Test.Base.__new__(cls, 2)


    *def **__init__*(self):

        pass


Michael


> ------------------------------------------------------------------------
>
> _______________________________________________
> Users mailing list
> Users at lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
>   


-- 
http://www.ironpythoninaction.com/
http://www.voidspace.org.uk/blog


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20090822/3566bc94/attachment.html>


More information about the Ironpython-users mailing list