473,767 Members | 1,627 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 2503
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
6425
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
1898
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
1219
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
1381
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
2948
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
3455
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
1557
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
1467
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
14573
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
9571
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
9405
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
10169
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
9841
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
8838
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
5280
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
5424
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3533
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2807
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.