[Tutor] /not/ instanciating

Kent Johnson kent37 at tds.net
Sun Nov 16 23:02:42 CET 2008

On Sun, Nov 16, 2008 at 2:57 PM, spir <denis.spir at free.fr> wrote:
> Hello,
> I have a type (say: T) which normally receives as main init argument an
> object that can be of any other type. Occasionally, this arg object may
> precisely be of type T. In this case, for several reasons, I wish not to
> "over-instanciate", rather that the constructor returns the source object
> unchanged. I did some research and trials on the topic, and found as sole
> solution to overload __new__ as shown below.

A simpler way to do this would be with a staticmethod or classmethod
that acts as an object factory. For example,

class T(object):
  def make(source):
    if type(source) == T:
      return source
    return T(source)

Then your client code calls T.make(source).


More information about the Tutor mailing list