return same type of object

Bruno Desthuilliers onurb at xiludom.gro
Tue Oct 24 16:44:14 CEST 2006


David Isaac wrote:
> Instances of MyClass have a method that
> returns another instance.  

This is usually known as a 'factory method'.

> Ignoring the details
> of why I might wish to do this, I could
> return MyClass()
> or
> return self.__class__()
>
> I like that latter better.  Should I?

You do realise that both solutions are *not* strictky equilavent, do you?

class PsychoRigid(object):
  def create(self):
    return PsychoRigid()

class PsychoRigidChild(PsychoRigid):
  pass

pr1 = PsychoRigidChild()
pr2 = pr1.create()
print "pr2 is a ", type(pr2)

class Virtual(object):
  def create(self):
    return self.__class__()

class VirtualChild(Virtual):
  pass

vc1 = VirtualChild()
vc2 = vc1.create()
print "vc2 is a ", type(vc2)


My 2 cents...
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list