how to create instances of classes without calling the constructor?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Tue Mar 18 09:10:26 EDT 2008
On Tue, 18 Mar 2008 01:08:45 +0100, Dominik Jain wrote:
> 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
>>> # Create a Spam instance the regular way
... a = Spam("args")
spam spam spam spam
>>> # And a Spam instance the unusual way
... b = empty_instance(Spam)
>>> a.args
('args',)
>>> b.args
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Spam' object has no attribute 'args'
--
Steven
More information about the Python-list
mailing list