473,835 Members | 1,794 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

__new__

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 object. There's nothing that requires that it return a
new object that is an instance of its class argument, although that is the
convention. If you return an existing object, the constructor call will still
call its __init__ method. If you return an object of a different class, its
__init__ method will be called.
"""

The quote implies that when I call carol, b.__init__ should be called.
However, this does not seem to be the case (see code below). What am I not
understanding? Shouldn't the interpreter call b.__init__ when b is returned
from carol.__new__?

James

py> class bob(object):
.... def __init__(self):
.... print self.x
.... x = 2
....
py> class carol(object):
.... def __new__(cls):
.... return b
....
py> b=bob()
py> b.x
2
py> c = carol() # should print "2"
py> c
<__main__.bob object at 0x404333cc>

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Nov 6 '05 #1
3 2614
James Stroud wrote:
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 object. There's nothing that requires that it
return a new object that is an instance of its class argument, although
that is the convention. If you return an existing object, the constructor
call will still call its __init__ method. If you return an object of a
different class, its __init__ method will be called.
"""

The quote implies that when I call carol, b.__init__ should be called.
However, this does not seem to be the case (see code below). What am I not
understanding? Shouldn't the interpreter call b.__init__ when b is
returned from carol.__new__?


Here's what "Python in a Nutshell" (p84) says:

"""
Each new-style class has a static method named __new__. When you call
C(*args, **kwds) to create a new instance of a new-style class C, Python
invokes C.__new__(C, *args, **kwds). Python uses __new__'s return value x
as the newly created instance. Then, Python calls C.__init__(x, *args,
**kwds), but only when x is indeed an instance of C (otherwise, x's state
is as __new__ had left it). Thus, for a new-style class C, the statement
x=C(23) is equivlent to the following code:

x = C.__new__(C, 23)
if isinstance(x, C): C.__init__(x, 23)
"""

If the following code says what I think it does

class A(object):
def __init__(self):
print "init A"
def __new__(cls):
return b
class B(A):
def __init__(self):
print "init B"
b = object.__new__( B)

print "---"
A() # prints 'init B'
A.__init__(b) # prints 'init A'
print "---"
b = 42
A() # prints nothing

the "Nutshell" example should be changed to

x = C.__new__(C, 23)
if isinstance(x, C): x.__init__(23)

to comply with the current implementation (I used Python 2.4).

Peter

Nov 6 '05 #2
Peter Otten <__*******@web. de> wrote:
...
is as __new__ had left it). Thus, for a new-style class C, the statement
x=C(23) is equivlent to the following code:

x = C.__new__(C, 23)
if isinstance(x, C): C.__init__(x, 23) ... the "Nutshell" example should be changed to

x = C.__new__(C, 23)
if isinstance(x, C): x.__init__(23)

to comply with the current implementation (I used Python 2.4).


Hmmm -- not quite, because in the new-style object model special methods
are taken from the type, NOT from the instance as the latter is saying.
E.g, if you change class B into:

class B(A):
def __init__(self):
print "init B"
def f(): print 'from instance'
self.__init__ = f

you'll see that while b.__init__() would print 'from instance',
instantiating A will not. I think the right correction to the Nutshell
is therefore:

x = C.__new__(C, 23)
if isinstance(x, C): type(x).__init_ _(x, 23)

and this is how I plan to have it in the 2nd edition.
Alex
Nov 6 '05 #3
James Stroud wrote:
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 object. There's nothing that requires that it return a
new object that is an instance of its class argument, although that is the
convention. If you return an existing object, the constructor call will still
call its __init__ method. If you return an object of a different class, its
__init__ method will be called.
"""


Any reason why you're looking at 2.2 documentation when you're running 2.3?

Anyway, the current docs corrected this mistake[1]

"""
If __new__() returns an instance of cls, then the new instance's
__init__() method will be invoked like "__init__(s elf[, ...])", where
self is the new instance and the remaining arguments are the same as
were passed to __new__().

If __new__() does not return an instance of cls, then the new instance's
__init__() method will not be invoked.
"""

[1]http://docs.python.org/ref/customization.h tml

STeVe
Nov 8 '05 #4

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

Similar topics

1
2311
by: Michele Simionato | last post by:
Let me show first how does it work for tuples: >>> class MyTuple(tuple): .... def __new__(cls,strng): # implicit conversion string of ints => tuple .... return super(MyTuple,cls).__new__(cls,map(int,strng.split())) >>> MyTuple('1 2') (1, 2) No wonder here, everything is fine. However, if I do the same for lists I get the following:
9
6232
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 nonetheless, so that the instance is initialized a second time. For example, please consider the following class (a singleton in this case): >>> class C(object): .... instance = None .... def __new__(cls): .... if C.instance is None:
5
2507
by: could ildg | last post by:
As there is already __init__, why need a __new__? What can __new__ give us while __init__ can't? In what situations we should use __new__? And in what situations we must use __new__? Can __new__ take the place of __init__? Thanks.
5
2163
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 examples. Lets say I want an int-derived class that is initilized to one greater than what it's constructor is given: class myint(int): def __new__(cls, intIn):
18
1715
by: Paulo da Silva | last post by:
Sorry to put here too many questions about __init__ __new__ stuff but I always found a new problem when using them. I have searched for simple __new__ docs on how to do the basic things but find none. After trying the solutions people gently posted here (thanks) I run into new trouble when I go with further development. Here is the new situation.
1
1207
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 observed by the following code: class A(object): def __new__(cls, *args, **kwds): print "A.__new__", args, kwds
5
1475
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 by changing as little code as possible. I also want the new exceptions to be a subclass of the old S3ResponseError so as to not break old code that catches it. If I meet these two requirements I expect my modification to make it into boto and then...
4
3550
by: Steven D'Aprano | last post by:
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: .... def __new__(cls, *args): .... print "__new__", args
3
2776
by: Torsten Mohr | last post by:
Hi, i have some questions related to new style classes, they look quite useful but i wonder if somebody can give me an example on constructors using __new__ and on using __init__ ? I just see that when using it i can't give parameters to __new__ and when i additionally define __init__ then __new__ is not called.
0
9802
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10517
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10230
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9343
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6961
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5632
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5802
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4430
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3990
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.