473,395 Members | 1,474 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Modify arguments between __new__ and __init__

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.

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

>>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?


--
Steven
Dec 23 '07 #1
4 3512
On Dec 22, 11:03 pm, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.auwrote:
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
Dec 23 '07 #2
Steven D'Aprano 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.

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

>>>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?
You can really only achieve this by writing a metaclass. When a new
object is created, what's first called is the __call__ method of the
type object. This basically looks like::

def __call__(cls, *args, **kwargs):
obj = cls.__new__(cls, *args, **kwargs)
obj.__init__(*args, **kwargs)
return obj

Hopefully that explains the behavior you're seeing. If you want
different behavior than this, you can change __call__ by defining your
own metaclass with a different __call__ method, for example::
>>class SpamMeta(type):
... def __call__(cls, *args, **kwargs):
... obj = cls.__new__(cls)
... obj.__init__('spam spam spam')
... return obj
...
>>class Spam(object):
... __metaclass__ = SpamMeta
... def __new__(cls, *args):
... print '__new__', args
... return object.__new__(cls)
... def __init__(self, *args):
... print '__init__', args
...
>>Spam()
__new__ ()
__init__ ('spam spam spam',)
<__main__.Spam object at 0x00E756F0>

Hope that helps,

STeVe
Dec 23 '07 #3
On Dec 23, 5:03*am, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.auwrote:
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.

I would like to modify the arguments after the __new__ method is called
but before the __init__ method, somewhat like this:
>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?

--
Steven
The ususal way is to override the __call__ method of the metaclass.

HTH

--
Arnaud

Dec 23 '07 #4
On Sat, 22 Dec 2007 23:01:50 -0700, Steven Bethard wrote:
Steven D'Aprano 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.

I would like to modify the arguments after the __new__ method is called
but before the __init__ method, somewhat like this:
[snip]
You can really only achieve this by writing a metaclass. When a new
object is created, what's first called is the __call__ method of the
type object. This basically looks like::
[snip]
That's an excellent explanation of how to use metaclasses!

Thanks Steve, and everyone else who answered. I'm not yet sure if that's
the approach I'm going to use (I may end up moving all the instance code
into __new__, or __init__, rather than splitting it) but that's an
interesting option for me to explore.
--
Steven
Dec 23 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Peter Olsen | last post by:
I want to define a class "point" as a subclass of complex. When I create an instance sample = point(<arglist>) I want "sample" to "be" a complex number, but with its real and imaginary...
8
by: Mark English | last post by:
I'd like to write a Tkinter app which, given a class, pops up a window(s) with fields for each "attribute" of that class. The user could enter values for the attributes and on closing the window...
9
by: Felix Wiemann | last post by:
Sometimes (but not always) the __new__ method of one of my classes returns an *existing* instance of the class. However, when it does that, the __init__ method of the existing instance is called...
2
by: Steven Bethard | last post by:
Felix Wiemann wrote: > Steven Bethard wrote: >> http://www.python.org/2.2.3/descrintro.html#__new__ > > > I'm just seeing that the web page says: > > | If you return an existing object,...
3
by: James Stroud | last post by:
Hello All, I'm running 2.3.4 I was reading the documentation for classes & types http://www.python.org/2.2.3/descrintro.html And stumbled on this paragraph: """ __new__ must return an...
5
by: Ken Schutte | last post by:
Hi, I'm been trying to create some custom classes derived from some of python's built-in types, like int and list, etc. I've run into some trouble, which I could explain with a couple simple...
1
by: Frank Benkstein | last post by:
Hi, the behaviour I always observed when creating instances by calling the class A is that '__init__' is always only called when the object returned by A.__new__ is an instance of A. This can be...
5
by: Sandra-24 | last post by:
Ok here's the problem, I'm modifying a 3rd party library (boto) to have more specific exceptions. I want to change S3ResponseError into about 30 more specific errors. Preferably I want to do this...
4
by: Ethan Furman | last post by:
Emile van Sebille wrote: Good point. What I'm curious about, though, is the comment in the code about making the Decimal instance immutable. I was unable to find docs on that issue. ~Ethan~
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.