subclassing pyrex extension types in python

Discussion in 'Python' started by Nitin, Jan 19, 2007.

  1. Nitin

    Nitin Guest

    Hi All

    I am trying to subclass an extension type in Python and add attributes
    to the new class but I keep getting errors. I read the "Extension
    Types" document on the Pyrex website but I couldn't get an answer from
    it.

    Here's the Spam extension type from Pyrex website:

    cdef class Spam:

    cdef int amount

    def __new__(self):
    self.amount = 0

    def get_amount(self):
    return self.amount

    Once compiled, here's how I am using this:

    import spam

    class mySpam(spam.Spam):
    def __init__(self, name1=None, name2=None):
    spam.Spam.__init__(self)
    self.name1 = name1
    self.name2 = name2

    When I run this Python code, I get an error "TypeError: 'name2' is an
    invalid keyword argument for this function"

    Is there something I need to know about Pyrex extension types and
    keyword arguments ? I tried to google for this but couldn't come up
    with anything.

    Thanks !
    Nitin
    Nitin, Jan 19, 2007
    #1
    1. Advertising

  2. Nitin

    greg Guest

    Nitin wrote:

    > I am trying to subclass an extension type in Python and add attributes
    > to the new class but I keep getting errors.
    >
    > cdef class Spam:
    >
    > cdef int amount
    >
    > def __new__(self):
    > self.amount = 0
    >
    > I get an error "TypeError: 'name2' is an
    > invalid keyword argument for this function"


    Arguments to the constructor of a class are passed
    to its __new__ method as well as its __init__ method,
    so if you want to subclass it in Python, you need to
    allow for that by defining it as

    def __new__(self, *args, **kwds):
    ...

    Without that, your Python subclass would have to define
    its own __new__ method which accepts the extra args
    and strips them out, e.g.

    class MySpam(Spam):

    def __new__(cls, name1=None, name2=None):
    return Spam.__new__(cls)

    --
    Greg
    greg, Jan 28, 2007
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?iso-8859-1?Q?Fran=E7ois?= Pinard

    Re: Pyrex without Python (was Re: calling Pyrex results from C)

    =?iso-8859-1?Q?Fran=E7ois?= Pinard, Jan 21, 2004, in forum: Python
    Replies:
    3
    Views:
    303
    A.M. Kuchling
    Jan 21, 2004
  2. gregory lielens
    Replies:
    6
    Views:
    595
    Gregory Lielens
    Dec 2, 2004
  3. Chris Lambacher
    Replies:
    0
    Views:
    666
    Chris Lambacher
    Jun 8, 2005
  4. Greg Ewing
    Replies:
    2
    Views:
    334
    Dieter Maurer
    Jun 29, 2006
  5. Replies:
    11
    Views:
    430
    Steve Holden
    Aug 30, 2007
Loading...

Share This Page