I am trying to create a class that doesn’t re-create an object with the same input parameters. When I try to instantiate a class with the same parameters that were used to create an already-existing object, I just want my new class to return a pointer to the already-created (expensively-created) object. This is what I have tried so far:
JavaScript
x
38
38
1
class myobject0(object):
2
# At first, I didn't realize that even already-instantiated
3
# objects had their __init__ called again
4
instances = {}
5
def __new__(cls,x):
6
if x not in cls.instances.keys():
7
cls.instances[x] = object.__new__(cls,x)
8
return cls.instances[x]
9
def __init__(self,x):
10
print 'doing something expensive'
11
12
class myobject1(object):
13
# I tried to override the existing object's __init__
14
# but it didnt work.
15
instances = {}
16
def __new__(cls,x):
17
if x not in cls.instances.keys():
18
cls.instances[x] = object.__new__(cls,x)
19
else:
20
cls.instances[x].__init__ = lambda x: None
21
return cls.instances[x]
22
def __init__(self,x):
23
print 'doing something expensive'
24
25
class myobject2(object):
26
# does what I want but is ugly
27
instances = {}
28
def __new__(cls,x):
29
if x not in cls.instances.keys():
30
cls.instances[x] = object.__new__(cls,x)
31
cls.instances[x]._is_new = 1
32
else:
33
cls.instances[x]._is_new = 0
34
return cls.instances[x]
35
def __init__(self,x):
36
if self._is_new:
37
print 'doing something expensive'
38
This is my first venture into overriding __new__
and I’m convinced I’m not going about it the right way. Set me straight, please.
Advertisement
Answer
First, use Upper Case Class Names in Python.
Second, use a Factory design pattern to solve this problem.
JavaScript
1
12
12
1
class MyObject( object ):
2
def __init__( self, args ):
3
pass # Something Expensive
4
5
class MyObjectFactory( object ):
6
def __init__( self ):
7
self.pool = {}
8
def makeMyObject( self, args ):
9
if args not in self.pool:
10
self.pool[args] = MyObject( args )
11
return self.pool[args]
12
This is much simpler than fooling around with new and having class level pools of objects.