__abs(self)__?
Sean 'Shaleh' Perry
shalehperry at attbi.com
Fri Mar 1 15:06:54 EST 2002
On 01-Mar-2002 Mike Carifio 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
>
> seems no different from:
>
> class ExampleNumber:
> def __init__(self, initializer):
> self.value = initializer
> def abs(self): # name isn't special?
> return abs(self.value)
>
> abs is a builtin function, so why do I need a special name for a function?
> I'm missing something...
>
the __foo__ method names are special because you do not call them directly
(usually) rather they are triggered when a request is made.
__abs__() causes the object to return a value that represents the absolute
value of the object's data, whatever that means.
abs(obj) translates into obj.__abs__(). This is just like 'print obj' calling
obj.__str__() or 'obj[i]' calling obj.__getitem__(i).
More information about the Python-list
mailing list