[Tutor] Overloading comparisons

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Nov 15 19:55:17 CET 2005



> I defined an object wich describes a video clip, like this
>
> class VideoSegment:
>      def __init__(self, filename):
>          # Attributes that have to be present
>          self.filename = filename

[some text cut]

> I can define the following for sorting the array:

[some code cut]

> But then I want to test for existance doing
>
> if 'lala.avi' in myarray:

[some text cut]


Hi Hugo,

Rather than directly use a list to hold those VideoSegments, you may want
to make a separate VideoContainer.  A quick and dirty approach would look
something like this:

#########################################
class VideoContainer:
    def __init__(self):
        self.segments = []

    def addSegment(self, segment):
        self.segments.append(segment)
        self.segments.sort()

    def deleteOldest(self): ...

    def __contains__(self, segmentName): ...
#########################################

The idea is to squirrel away the sorted list in this VideoContainer, and
not expose that implementation detail directly to people.  Why do we use a
list?  Why not a hash?  Why does the list have to be sorted?

Those are implementation details that we want to hide, just in case we
have to change our mind on how to effectively hold those Segments.  As far
as the world's concerned, a VideoContainer is something that we can put
VideoSegments in, and where we can drop old segments off.

(And if your operations are limited to this, you might even use something
like the 'heapq' module if you're concerned about efficiency.  See:
http://www.python.org/doc/lib/module-heapq.html for details.)


It should be the container's responsibility to keep the segments sorted
any time we add a new segment in.  The container can also know how to
check for segments by name (with the __contains__() function.)

Trying to have VideoSegment.__cmp__() to somehow juggle both the sorting
role and the existence checking role might not be a good idea.  You're
doing two distinct things, and I think they should be two different
methods.  And from a design perspective, I think that existence-checking
method should go in a class like VideoContainer.


Best of wishes!



More information about the Tutor mailing list