__abs(self)__?

Carel Fellinger cfelling at iae.nl
Fri Mar 1 16:54:11 EST 2002


Mike Carifio <carifio.nospam at nospam.usys.com> wrote:
> I'm reading about special method names. __abs__(self), which maps to the
> abs() method seems unneccessary(?).
> So:

> class ExampleNumber:
>     def __init__(self, initializer):
>         self.value = initializer
>     def __abs__(self):
>         return abs(self.value)

>>>> x = ExampleNumber(-1)
>>>> x.abs()
> 1

strange, you haven't defined a method `abs' for `ExampleNumber's!
I would expect:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: ExampleNumber instance has no attribute 'abs'
>>>

unless you typed:

 >>> abs(x)

in which case x.__abs__() is called under the hoods.

> abs is a builtin function, so why do I need a special name for a function?
> I'm missing something...

many builtins work on instances of user defined classes by expecting
a special named method (those methods names are easily recognizable
due to the leading and trailing double underscores)

So you have a generic builtin fucntion abs, you use it on integers and
homebrew number classes alike, `abs(instance)' and all works as it should.


-- 
groetjes, carel



More information about the Python-list mailing list