subclassing pyrex extension types in python

N

Nitin

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
 
G

greg

Nitin said:
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)
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top