how to create instances of classes without calling the constructor?

D

Dominik Jain

Hi!

Does anyone know how an instance of a (new-style) class can be created
without having to call the constructor (and providing the arguments it
requires)? With old-style classes, this was possible using new.instance.
Surely there must be a simple way to do this with new-style classes, too --
or else how does pickle manage?

Best,
Dominik
 
C

castironpi

Hi!

Does anyone know how an instance of a (new-style) class can be created
without having to call the constructor (and providing the arguments it
requires)? With old-style classes, this was possible using new.instance.
Surely there must be a simple way to do this with new-style classes, too --  
or else how does pickle manage?

Best,
Dominik
<__main__.C object at 0x00B5ED70>

And for the record:
... def __init__( self ):
... print( 'in init' )
...in init
in init
<__main__.C object at 0x00B5ED90>

Which is kind of biza-a-r-rre.
 
S

Steven D'Aprano

Hi!

Does anyone know how an instance of a (new-style) class can be created
without having to call the constructor (and providing the arguments it
requires)? With old-style classes, this was possible using new.instance.
Surely there must be a simple way to do this with new-style classes, too
-- or else how does pickle manage?

I don't think you can create an instance without calling __new__. (At
least not without all sorts of metaclass tricks.) Creating the instance
is what __new__ does.

But you can create a new instance without calling the initialiser
__init__. Here's a variation on a recipe from Alex Martelli:


class Spam(object):
def __init__(self, *args):
print "spam spam spam spam"
self.args = args


def empty_instance(cls):
class Empty(cls):
def __init__(self): pass
x = Empty()
x.__class__ = cls
return x


.... a = Spam("args")
spam spam spam spamTraceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Spam' object has no attribute 'args'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top