Jump to content


Ch7 Typeerror. Why?

  • Please log in to reply
1 reply to this topic

#1 KFunk


    New Member

  • Members
  • Pip
  • 1 posts

Posted 12 July 2013 - 03:13 PM

See page 249-250.

I didn't quite understand why this caused an error. I assume that when the .top3() method runs, it returns a list. Why does this throw an error? I understand why the solution works( .top3 attribute instead of .top3() method ), but I don't understand why python doesn't like the original method call.

I'm coming from a Java background, if that gives you any insight to my confusion.

#2 paulbarry


    Advanced Member

  • O'Reilly Author
  • PipPipPipPipPipPipPipPip
  • 307 posts

Posted 13 July 2013 - 08:12 AM

TypeErrors can occur for many different reasons in Python. The trick to understanding this one is to look at the rest of the error message: "list object is not callable". What Python is saying is that (in this case) trying to treat a list as if it is a method is not allowed - that's what the () do, i.e., they ask Python to call something. There's a TypeError here as the calling code is treating the list as if it is something other than a list - which Python thinks is silly, hence the error. When you use the @property tag in a class (before the method definition), you are explicitly telling Python not to allow "regular" method calls to that method (which I'll admit does sound a little bit strange). The method becomes an attribute of the class... in the book's example, the top3 method becomes a list attribute of the class due to the use of @property. It is, for all intents and purposes, no longer a method as far as users of the class are concerned.

Does this explanation make sense? The one in the book does need to be beefed-up. Thanks for drawing this to my attention.


0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users