Summer reading list

John J. Lee jjl at pobox.com
Sat Aug 16 18:47:11 EDT 2003


mis6 at pitt.edu (Michele Simionato) writes:

> jjl at pobox.com (John J. Lee) wrote in message news:<87ekzmsi5c.fsf at pobox.com>...
> > mis6 at pitt.edu (Michele Simionato) writes:
> > > To reuse classes is good, but typically only works when you know
> > > about the class you want to inherit *before* you start coding your
> > > own class; on the other hand, it is quite easy to add functions
> > > or methods to your class even *after* you wrote it.
> > [...]
> > 
> > But I don't think that makes any sense.  As I'm certain you know,
> > there would be nothing to stop you using a class in exactly the same
> > way you used the function, because reuse != inheritance.  Functions
> > can be implemented in terms of classes, and classes can be implemented
> > in terms of functions.
> 
> Let me see if I understand what you mean. You are saying "I could invoke
> an instance method just as I invoke a function, without using inheritance,
> and reuse the method in another class". True, but this is clumsy: the point 

I don't think composition is clumsy.


> of using a class is making use of inheritance for code reuse,  otherwise I 
> could just use a function, isn't it?

Composition doesn't preclude inheritance in the class hierarchy you're
reusing by composition.  In fact, that's usually what happens.  And
extension of interfaces (which is what you were talking about,
presumably with implementation inheritance of the old methods) isn't
the only useful thing about classes -- associating functions with data
is useful on its own, as is plain old interface inheritance without
extension.


> Besides, typically an instance
> method is doing something to the 'self' argument and may have unwanted
> side effects on the object; a function is safer in this respect.

I don't understand.

class foo:
    def ni(self): print "ni"

class bar:
    def __init__(self): self.foo = foo()
    def NININI(self):
        for i in range(3): self.foo.ni()


> In my experience, it takes a certain effort to code a reusable class; 
> it takes a much lesser effort to code a reusable function.

s/reusable class/inheritable class/, and add the proviso that it's
just as easy to reuse classes by composition as it is functions, and
I'd agree.  But you knew that!


> > The only reason it's good that Python library uses functions sometimes
> > instead of classes is as you say: KISS.  If it only needs a function,
> > use a function.
> > 
> > John
> 
> Yep.
> 
>        Michele


John




More information about the Python-list mailing list