Defining a method final

holger krekel pyth at devel.trillke.net
Tue Jun 11 15:32:30 CEST 2002


Hello Fabio,

[you explained]
> I would like to define a method for a class which has
> not to be overriden. Of course, since the developer of
> this project are two, this could be established by
> convention, but if the project will grow consistently 
> another developer could override the method by mistake,
> causing unpleasant side effects.

I see. But did you know that usually pythonic objects work like this:

class stream:
    def readline(self):
        return ..someline...

class filestream:   # no inheritance needed!
    def readline(self):
        return ..readfromfile...

and that a method wanting to have an instance which it can
call readline on, would not need to check types etc...

def tokenize(provider):
    l=provider.readline()

works with a stream or a filestream-instance, it even works
with a 'file' instance or a StringIO-instance :-)

I imagine that this might sound fragile to you. But you
spare yourself and other a *lot* of effort if you don't
insist on exact type checking but rather use the
*behaviour* of objects. After all, working with behaviour 
is the great promise of OOP and python has it. Java/C++
would require you to group all objects into an
inheritance-hierarchy which usually makes things *more* 
difficult and verbose. 

OTOH for big enough programs (say >50.000 LOC) you should:

- write many tests which thoroughly check for desired behaviour
  (ask Peter Hansen for more details:-)

- dig deeper into 'interface' concepts for python. It's 
  also discussed on python-lists from time to time...

not that someone will certainly point out, that you should
write tests for smaller programs, too :-)

regards,

    holger





More information about the Python-list mailing list