[Tutor] Python Class functionality idiosyncrasy..
Gonçalo Rodrigues
op73418 at mail.telepac.pt
Wed Oct 22 06:58:34 EDT 2003
On Wed, 22 Oct 2003 15:50:58 +0530, you wrote:
>Dear Friends,
> While just playing arnd with Python .. I just came across
>this curious implementation of Python Object Oriented
>Techniques..
>
>The base class here is calling a function of the derived
>class even befre the function of the derived class is
>defined..A similar implementation in C++ would not even
>compile.. My question is doesnt this implementation break
>some tennants of OO techniques ??
What tenets (not tennants I believe :-) are being broken?
>How can the base class
>call functions of the derived class ??
>
I'm not sure I understand your question. Your example below shows how
that is done.
>>>> class base1 :
>... def baseFunc1( self ):
>... print "Base class Function"
>... self.derivedFunc()
>...
>>>> class derived( base1 ):
>... def derivedFunc(self ):
>... print "derived Func.."
>...
>>>> b = base1()
>>>> b.baseFunc1()
>Traceback (most recent call last):
> File "<stdin>", line 1, in ?
>TypeError: unbound method baseFunc1() must be called with
>base1 instance as first argument (got nothing instead)
>
>>>> d = derived()
>>>> d.baseFunc1()
>Base class Function
>derived Func..
>>>>
>
This is called the template pattern. You have a base class providing
some functionality implemented in terms of some other, *not*
implemented methods. This class is not meant to be intantiated by
itself, it is what is called an abstract class, and it's customary to
put:
class AbstractClass(object):
def __init__(self, *args, **kwargs):
raise NotImplementedError("Class not to be intantiated.")
...
What you do is derive from that class and implement the missing
methods. The example you gave explains it: The base class implements a
method baseFunc1 in terms of derivedFunc. If you call it on a base1
instance and it will obviously fail because there is no such method.
But on a derived instance, it does not fail because you have
implemented the derivedFunc method.
Somewhere in the net there are some slides by Alex Martelli (the
martellibot) explaining the template pattern. I'm having trouble with
the internet right now, but I'll get back to you if I can get hold of
the url.
Hope it helps, with my best regards,
G. Rodrigues
More information about the Tutor
mailing list