Removing objects of a superclass?

Tim Peters tim_one at email.msn.com
Tue Feb 1 23:26:10 CET 2000


[Gerrit Holl]
> is it possible to _remove_ objects of a superclass?
> I'm interested in creating a sort of UserString, and because it
> shares many methods with UserList I want to subclass it. But
> then, I need to remove some methods like .append and .pop. Can
> I do that?

By deriving UserString from UserList, you're announcing to the world that a
UserString "is a" UserList.  But if UserString doesn't support a superset of
the methods provided by UserList, it's not really a UserList at all, so
you're lying <wink>.  Really, in most circles this would be considered a
sure sign of confused design.

Some languages cater to this kind of lying anyway, but Python does not.  You
would need to override the unwanted methods in UserString, as in

    class UserString(UserList):

        def pop(self):
            raise IWasLyingError("despite that I told you a string"
                                 " is a list, you can't pop it")

More principled approaches include:

+ Move the functionality the classes have in common into a third class, and
derive from that instead.  This is clean.  In the case of UserList, it also
means rewriting part of the std Python library <wink>.  This kind of thing
is called "refactoring", and is depressingly (or delighfully <wink>) common
as OO designs get larger and larger.

+ Use a "has a" relationship (as opposed to "is a") instead.  That is, a
UserString object simply contains a UserList object as a member.  No
subclassing.  Then the only methods that are visible are those you
explicitly provide.  If there are a great many UserString methods that could
be passed on to the UserList method directly, you can play __getattr__
tricks to avoid writing a great many individual "forwarding" methods.

+ Rethink the whole problem:  maybe .pop and .append etc really would be
useful in a UserString!  They're sure useful for lists, and it's not insane
to picture a string as a list of characters.

+ Study the std array module, to see whether an array of characters already
does everything you want a UserString to do.

cheating-is-much-better-than-lying<wink>-ly y'rs  - tim






More information about the Python-list mailing list