[Tutor] instantiating subclass by parameter

Karl Fast karl.fast at pobox.com
Tue Oct 28 13:01:34 EST 2003


I've got a class with two subclasses. I need to create an instance
of a particular subclass, inheriting from the superclass, but I want
to do it by passing a parameter to the super class. 

I'm probably not describing this very well. Some sample code might
help.

This doesn't work, but I think it illusrates what I'm going for...

class WebSearch:
    def __init__(self, engine):
        self.name = engine    
        if engine == 'altavista':
            self = Altavista.__init__()
        elif engine == 'alltheweb':
            self = AlltheWeb.__init__()

    def foo(self):
       print "inherited foo"

    def bar(self):
       print "inherited bar"
       
class Altavista(WebSearch):
    def __init__(self):
        pass

    def foo(self):
       print "altavista foo"    

class AlltheWeb(WebSearch):
    def __init__(self):
        pass
  
    def bar(self):
        print "alltheweb bar"


The idea is that if I create instances, like so, then I'll get these
results:

  >>>  a = WebSearch('altavista')
  >>>  b = WebSearch('alltheweb')
  >>>  a.name
  altavista
  >>>  b.name
  alltheweb  
  >>>  a.foo()
  altavista foo
  >>>  b.bar()
  alltheweb bar  
  >>>  a.bar()
  inherited bar
  >>>  b.foo()  
  inherited foo

Does that make sense?


--karl



More information about the Tutor mailing list