subclassing pyrex extension types in python

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Nitin

    #1

    subclassing pyrex extension types in python

    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.Spa m):
    def __init__(self, name1=None, name2=None):
    spam.Spam.__ini t__(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

  • greg

    #2
    Re: subclassing pyrex extension types in python

    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__(cl s)

    --
    Greg

    Comment

    Working...