[Tutor] Object defined by initialization parameters

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Apr 24 20:20:28 CEST 2006



On Mon, 24 Apr 2006, Andre Engels wrote:

> Is it possible to define a class in such a way, that if twice an object 
> is made with the same initialization parameters, the same object is 
> returned in both cases?

Yes.  The idea is to have the "constructor" really be a function that 
delegates off to actual object instantiation only after it's comfortable 
with the situation.  That is, we can make a "factory" function.

For example:

##############################
class _Boolean:
     def __init__(self, value):
         self.value = value

def Boolean(b):
     if b:
         return _Boolean(True)
     else:
         return _Boolean(False)
##############################

The idea is that no one should directly call the underscored _Boolean(): 
they should go through Boolean(), which can do some additional things to 
make sure clients get the canonical objects.


More information about the Tutor mailing list