[Tutor] instantiating subclass by parameter
Lloyd Kvam
pythontutor at venix.com
Tue Oct 28 14:06:19 EST 2003
class Altavista(WebSearch):
def __init__(self):
WebSearch.__init__(self, 'altavista')
The child class __init__ needs to call its parent __init__.
So now you would have:
a = Altavista()
to create an Altavista based instance.
You can have a "factory" function that calls the proper class
Recent Python improvements involve "new style" classes. amk publishes the
what's new in python notes.
http://www.python.org/doc/2.2.3/whatsnew/whatsnew22.html
What's New in Python 2.2
There are benefits to making object your base class. You would
change WebSearch to inherit from object. Then the __init__ method
would be coded:
class WebSearch(object):
...
class Altavista(WebSearch):
def __init__(self):
super(Altavista, self).__init__(self, 'altavista')
Also, classes have a special attribute: __name__ which is (surprise)
the name of the class. The WebSearch __init__ could use
self.__class__.__name__ rather than a parameter.
Hope this helps.
Karl Fast wrote:
> 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
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-653-8139
fax: 801-459-9582
More information about the Tutor
mailing list