Modify arguments between __new__ and __init__

davisn90210 at gmail.com davisn90210 at gmail.com
Sun Dec 23 00:36:11 EST 2007


On Dec 22, 11:03 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> When you call a new-style class, the __new__ method is called with the
> user-supplied arguments, followed by the __init__ method with the same
> arguments.
>

Only if __new__ returns an object of the type passed into __new__.
Otherwise, __init__ is not called.

> I would like to modify the arguments after the __new__ method is called
> but before the __init__ method, somewhat like this:
>

What's your use-case?  I mean, why not just do this in __init__
instead of __new__?

> >>> class Spam(object):
>
> ...     def __new__(cls, *args):
> ...             print "__new__", args
> ...             x = object.__new__(cls)
> ...             args = ['spam spam spam']
> ...             return x
> ...     def __init__(self, *args):
> ...             print "__init__", args  # hope to get 'spam spam spam'
> ...             return None
>
> but naturally it doesn't work:
>
> >>> s = Spam('spam and eggs', 'tomato', 'beans are off')
>
> __new__ ('spam and eggs', 'tomato', 'beans are off')
> __init__ ('spam and eggs', 'tomato', 'beans are off')
>
> Is there any way to do this, or am I all outta luck?
>

>From what I can tell from http://docs.python.org/ref/customization.html,
you are out of luck doing it this way unless you jury rig some way to
have __new__ return an object of a different type.

--Nathan Davis



More information about the Python-list mailing list