Forgetting "()" when calling methods

Bengt Richter bokr at oz.net
Sat Apr 26 12:57:01 EDT 2003


On Fri, 25 Apr 2003 23:46:50 +0200, Frantisek Fuka <fuka at fuxoft.cz> wrote:

>When I try to call methods, I sometimes forget to include the 
>parentheses. Instead of:
>
>if object.isGreen():
>	do something...
>
>i sometimes write:
>
>if object.isGreen:
>	do something...
>
>If I understand it correctly, the if statement in this case tests if 
>pointer to hasParent method is non-zero, which is of course always True 
>so no error is reported and "do something..." always gets executed, so 
>the application behaves in quite different way than I expected.
>
>You can say to me "Don't forget to always include the parenteses" but 
>I'm still curious if this cannot be somehow configured, so that I get 
>error when I try to just access the method pointer (".isGreen") instead 
>of calling the method (".isGreen()"). I understand that there has to be 
>the possibility of accessing the method pointers but I usually don't 
>need it and for a beginner like me this makes the applications very hard 
>to debug.
>
I think it's easier to do it the other way around. I.e., always leave off
the parenthesis, and make your isGreen a property if it has to be
evaluated each time it's accessed. The get-function of the property would
then return a bool (1 or 0 or True of False) and if you put () on that you
would get an exception. Type
    help(property)
for more info. Don't forget to derive your class from object if you want
to define properties for it.

Some people get nervous about the ambiguity of an attribute name that
doesn't just dereference to an object, but calls a method instead.
You might want to call special attention to property usage in the docs
for your class if there's anything tricky at all. But it is nice
to be able to write stuff like widget.bgcolor='lime' and have a visual
side effect if desired, etc. Some prefer widget.setBgColor('lime') though.
OTOH, properties let you add side effects to ordinary attributes without
changing the accessing code.

Regards,
Bengt Richter




More information about the Python-list mailing list