Method or function?

Michael Hudson mwh21 at cam.ac.uk
Sat Nov 4 08:31:43 EST 2000


Thomas Wouters <thomas at xs4all.net> writes:

> 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.

You don't really have to get that fancy:

>>> class C: 
...  pass
... 
>>> c=C()
>>> c.a = 1
>>> -c.a
-1
>>> -c
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'C' instance has no attribute '__neg__'

... which is what I'd expect at least (it's one of these things where
I'm more likely to get it right if I *don't* think about it!).

Cheers,
M.

-- 
  This makes it possible to pass complex object hierarchies to 
  a C coder who thinks computer science has made no worthwhile
  advancements since the invention of the pointer.
                                       -- Gordon McMillan, 30 Jul 1998



More information about the Python-list mailing list