473,722 Members | 2,168 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to use "__new__"?

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.
Jul 18 '05 #1
5 2500
could ildg wrote:
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__?


I believe the current documentation will be updated when 2.4.1 is
released, but documentation for __new__ is now available at:

http://www.python.org/dev/doc/devel/...omization.html

In short, you could use __new__ in place of __init__, but it's probably
only useful to do so if you need to change an instance *before* it's
created. In general, if you aren't subclassing an immutable type, and
you're not sure that you need __new__, you probably don't.

STeVe
Jul 18 '05 #2
Thank you.
I'm clear after I read the doc:
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.

__new__() is intended mainly to allow subclasses of immutable types
(like int, str, or tuple) to customize instance creation.
On Tue, 29 Mar 2005 18:12:41 -0700, Steven Bethard
<st************ @gmail.com> wrote:
could ildg wrote:
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__?


I believe the current documentation will be updated when 2.4.1 is
released, but documentation for __new__ is now available at:

http://www.python.org/dev/doc/devel/...omization.html

In short, you could use __new__ in place of __init__, but it's probably
only useful to do so if you need to change an instance *before* it's
created. In general, if you aren't subclassing an immutable type, and
you're not sure that you need __new__, you probably don't.

STeVe
--
http://mail.python.org/mailman/listinfo/python-list

Jul 18 '05 #3
Am Mittwoch, 30. März 2005 03:27 schrieb could ildg:
Thank you.
I'm clear after I read the doc:
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.

__new__() is intended mainly to allow subclasses of immutable types
(like int, str, or tuple) to customize instance creation.


Remember that __new__() can also be used to create singletons (to return a
pre-existing instance in case some form of argument matches, for example):

class Singleton(objec t):
__buffer = {}

def __new__(cls,som earg):
if somearg not in cls.__buffer:
cls.__buffer[somearg] = super(cls,Singl eton).__new__(c ls)
return cls.__buffer[somearg]

def __init__(self,s omearg):
self.__somearg = somearg

def __repr__(self):
return "<Singleton : %s at %s>" % (self.__somearg ,hex(id(self)))
x = Singleton(1)
y = Singleton(2)
z = Singleton(1)
print x <Singleton: 1 at -0x4840d934> print y <Singleton: 2 at -0x4840d914> print z <Singleton: 1 at -0x4840d934> x is y False x is z True y is z

False

You could extend the above example quite easily to deal with deallocation (a
reference to each created singleton is retained using the above class,
always, as long as the program is running) and also to make it threadsafe or
to disable initialization in case the singleton has already been initialized
before.

--
--- Heiko.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQBCShCbf0b pgh6uVAMRAqhqAJ 4heiYC24zpnGC0V p9dKU4exN3DJgCd GPtB
IteiPzZBBumSXSw 6M/VcmYs=
=ew0P
-----END PGP SIGNATURE-----

Jul 18 '05 #4
Am Mittwoch, 30. März 2005 04:36 schrieb Heiko Wundram:
You could extend the above example quite easily to deal with deallocation
(a reference to each created singleton is retained using the above class,
always, as long as the program is running) and also to make it threadsafe
or to disable initialization in case the singleton has already been
initialized before.


Just to post a complete example of a Singleton class which works in a
multithreaded environment, and allows you to update future instances (a
sample, untested implementation) :

<code>
import threading
import weakref

class SingletonBase(o bject):
__buffer = {}
__bufferLock = threading.RLock ()

def __new__(cls,*ar gs,**kwargs):
cls.__bufferLoc k.acquire()
try:
inst = cls.__create_ne w__(buffer,*arg s,**kwargs)
if not hasattr(inst,"_ SingletonBase__ instanceLock"):
inst.__instance Lock = threading.RLock ()
inst.__initiali zed = False
return inst
finally:
cls.__bufferLoc k.release()

@classmethod
def __create_new__( cls,*args,**kwa rgs):
return super(Singleton Base,cls).__new __(cls)

def __init__(self,* args,**kwargs):
self.__instance Lock.acquire()
try:
if not self.__initiali zed:
self.__initiali ze_new__(*args, **kwargs)
self.__initiali zed = True
else:
self.__update_o ld__(*args,**kw args)
finally:
self.__instance Lock.release()

def __initialize_ne w__(self,*args, **kwargs):
pass

def __update_old__( self,*args,**kw args):
pass

class Singleton(Singl etonBase):

@classmethod
def __create_new__( cls,buffer,some arg):
inst = buffer.get(some arg,lambda: None)()
if inst is None:
inst = super(Singleton ,cls).__create_ new__(cls)
buffer[somearg] = weakref.ref(ins t)
return inst

def __initialize_ne w__(self,somear g):
print "Initializi ng new instance."
self.__somearg = somearg

def __update_old__( self,somearg):
print "Updating old."
assert somearg == self.__somearg

# Initialize three singletons.
print "Creating singletons for 1, 2, 1."
x = Singleton(1)
y = Singleton(2)
z = Singleton(1)

# Print them out.
print "\nThree singletons: x, y, z."
print repr(x)
print repr(y)
print repr(z)

# Assert that x is not y, and x is z.
print "\nx is y, x is z"
print x is y
print x is z

# Delete names, and make sure weakrefs are unbound.
print "\nRemove all three singletons."
del x
del y
del z

# Recreate singleton for value 1.
print "\nRecreati ng singleton for value 1."
x = Singleton(1)
y = Singleton(1)

# Print them out.
print "\nNew Singleton(1): x, y."
print repr(x)
print repr(y)

# Check that x is y.
print "\nx is y"
print x is y
</code>

The above program prints the following output when run:

<output>
Creating singletons for 1, 2, 1.
Initializing new instance.
Initializing new instance.
Updating old.

Three singletons: x, y, z.
<__main__.Singl eton object at 0xb7bfbc6c>
<__main__.Singl eton object at 0xb7bfbcac>
<__main__.Singl eton object at 0xb7bfbc6c>

x is y, x is z
False
True

Remove all three singletons.

Recreating singleton for value 1.
Initializing new instance.
Updating old.

New Singleton(1): x, y.
<__main__.Singl eton object at 0xb7bfbc6c>
<__main__.Singl eton object at 0xb7bfbc6c>

x is y
True
</output>

HTH!

--
--- Heiko.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQBCShdSf0b pgh6uVAMRAmIMAJ 9EzsSRebvDog6ti xm3MEp3OXBDngCb B6Eu
OYud8wmgcKUyODe dkrW4PAQ=
=P8Nt
-----END PGP SIGNATURE-----

Jul 18 '05 #5

"could ildg" <co*******@gmai l.com> wrote in message
news:31******** *************** *@mail.gmail.co m...
__new__() is intended mainly to allow subclasses of immutable types
(like int, str, or tuple) to customize instance creation.


Exactly. It is an anwer to the conundrum: How do you give an immutable
object its unchangeable value. It is much like how to move an unmovable
object to its permanent position ;-).

TJR

Jul 18 '05 #6

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

Similar topics

3
6422
by: Jules Dubois | last post by:
I'm want to create a superclass with nothing but attributes and properties. Some of the subclasses will do nothing but provide values for the attributes. (I'd also like to make sure (1) that the subclass provides actual values for the attributes and (2) that no "client" module adds or removes attributes or properties, but I don't know how to do those.) I don't understand what I'm doing wrong, or maybe what I want to do is impossible. ...
6
1897
by: Uwe Mayer | last post by:
Hi, when extending a build in class, what does the constructor __init__(...) have to return? and how does the constructor call its base-class construtor? (or is this done automatically?) I want to derive from "file" to create a class that reads record from a binary file:
0
1213
by: Irmen de Jong | last post by:
I created my first ever Python Meta Class to solve a problem I'm having. I have an existing class that I want to make thread-safe: all method calls should use a thread-lock to avoid having multiple threads active in the class at the same time. I don't want to change every method of the class by adding lock.acquire()...try...finally..lock.release() stuff, so I decided to try it with a Meta Class. Below is what I came up with (after a bit...
7
1380
by: newseater | last post by:
Hello. I need to be able to control how objects are created. Sometimes when creating an object, i want to reuse another object instead. I've searched for factory method implementations and singleton implementations. They were too much of a hack! My first attempt of doing this was to play around with the __new__() method. But i didn't quite succed. Then i came up with making a static method which can create my instances or re-use other...
28
2941
by: Steven Bethard | last post by:
Ok, I finally have a PEP number. Here's the most updated version of the "make" statement PEP. I'll be posting it shortly to python-dev. Thanks again for the previous discussion and suggestions! PEP: 359 Title: The "make" Statement Version: $Revision: 45366 $ Last-Modified: $Date: 2006-04-13 07:36:24 -0600 (Thu, 13 Apr 2006) $
42
3437
by: Holger | last post by:
Hi guys Tried searching for a solution to this, but the error message is so generic, that I could not get any meaningfull results. Anyways - errormessage: ---------------------------------------------------- TypeError: addFile() takes exactly 1 argument (2 given) ----------------------------------------------------
3
1555
by: davidfinance | last post by:
Ok, maybe this is a stupid question, but why can't I make a subclass of datetime.date and override the __init__ method? --- from datetime import date class A(date): def __init__(self, a, b, c, d): print a, b, c, d
4
1465
by: Christian Joergensen | last post by:
Hello I stumpled upon this "feature" during my work tonight, and found it a bit confusing: .... class C: .... foobar = 42 .... .... <class __main__.C at 0xb7cf735c>
5
14570
by: akonsu | last post by:
hello, i need to add properties to instances dynamically during run time. this is because their names are determined by the database contents. so far i found a way to add methods on demand: class A(object) : def __getattr__(self, name) : if name == 'test' : def f() : return 'test'
0
8863
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
8739
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9384
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9238
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
8052
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...
1
6681
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5995
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
4762
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2602
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.