Method or function?

Thomas Wouters thomas at xs4all.net
Fri Nov 3 07:31:18 EST 2000


On Fri, Nov 03, 2000 at 10:27:31AM +0100, Rob Hooft wrote:
> >>>>> "CC" == Cliff Crawford <cjc26 at nospam.cornell.edu> writes:

>  CC> some of the functions on your list, like abs, only apply to
>  CC> numbers; do you really want to write (-4).abs() instead? ;)

> Not to mention the problems with -4.abs() and -4.0.abs() [the method
> should bind tighter than the unary minus?] [Does this parse?]

The float one parses just fine:

>>> -4.0.abs()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'float' object has no attribute 'abs'

the int one needs parentheses to disambiguate:

>>> -4.abs()
  File "<stdin>", line 1
    -4.abs()
         ^
SyntaxError: invalid syntax
>>> (-4).abs()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'int' object has no attribute 'abs'

As for what binds tighter, the minus or the method call, that's easy. Not
because it's obvious what the answer should be, but because it's already
perfectly valid syntax. It's just that int and float objects don't have
attributes. For example:

>>> class Negtest:
...     def __neg__(self):
...             print "__neg__ called on Negtest."
... 
>>> class Methtest:
...     def __neg__(self):
...             print "__neg__ called on Methtest."
...     def abs(self):
...             print "__abs__ called on Methtest."
...             return Negtest()
... 
>>> 
>>> m = Methtest()
>>> -m
__neg__ called on Methtest.
>>> -m.abs()
__abs__ called on Methtest.
__neg__ called on Negtest.


-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list