constructor of subclass and base's tp_new() (was: subclassing a new-style (C) extension type: help!)

Alex Martelli aleax at aleax.it
Wed Mar 26 18:42:35 EST 2003


Maciej Kalisiak wrote:
   ...
> | from State import State
> | class StateOfSize5(State):
> |     def __init__(self):
> |         State.__init__(self, 5)
> |     
> | s = State(5)                # this runs OK
> | s = StateOfSize5()  # ERROR
> | s = StateOfSize5(5)   # a workaround, but undermines the purpose of
> | subclass
> `----
> 
> The error I get is:
>   TypeError: state_new() takes exactly 1 argument (0 given)
> 
> Now, this makes sense, since before StateOfSize5.__init__() can be called,
> `self' must be already instantiated... but then, how do I go about
> achieving what I want? (i.e., to encapsulate the State initialization arg
> in the subclass)
> 
> I seem to recall that tp_init() corresponds to FooClass.__init__(), so
> it's as if I'm trying to directly frob tp_new() in the subclass...

If that's so (haven't followed the details in your earlier parts), then
maybe what you want to do is:

class StateOfSize5(State):
    def __new__(cls):
        return State.__new__(cls, 5)


Alex





More information about the Python-list mailing list