[Tutor] subclass

Kent Johnson kent37 at tds.net
Fri Feb 3 17:57:11 CET 2006


Christopher Spears wrote:
> Here is a problem I'm working on out of Learning
> Python:
> 
> Make a subclass of MyList from exercise 2 called
> MyListSub which extends MyList to print a message to
> stdout before each overloaded operation is called and
> counts the number of calls.  MyListSub should inherit
> basic method behavoir from MyList.  Adding a sequence
> to a MyListSub should print a message, increment the
> counter for + calls, and perform the superclass's
> method.
> > 
> However, I keep wondering if there is a more elegant
> way to do this like create some sort of function that
> does this:
> 
> if a method is called:
>     print a message
> 
> if a method is called:
>     increment a counter for that method

You could do this by overriding __getattribute__ in MyListSub. This 
would allow you to put all the printing and counting code in one place. 
This is an elegant solution that will probably cause you a couple of 
stack overflows before you get it right.
http://docs.python.org/ref/new-style-attribute-access.html

You could also write a decorator that adds printing and counting 
behaviour to a method. You would have to apply the decorator to each 
method. I suppose you could apply the decorator in a metaclass...but I 
would try the __getattribute__ approach first.

Neither of these approaches are really beginner exercises...
Kent




More information about the Tutor mailing list