tags:

views:

212

answers:

4

(I'm sure this is a FAQ, but also hard to google)

Why does Python use abs(x) instead of x.abs?

As far as I see everything abs() does besides calling x.__abs__ could just as well be implemented in object.abs()

Is it historical, because there hasn't always been a root class?

+1  A: 

I think you are looking a typical example where a language designer decides that readability and terseness trump purist constructs.

ojblass
A: 

i think it involves how object oriented way python has been used, because the first parameter of method calls on object is the object itself, so x.abs() is in essential abs(x)

look at the follow page under chapter 3.2.3 Python supports object-oriented programming

that should explain some things

Rockfly
x.abs() is *not* abs(x), it's C.abs(x) where C is the class of x. That's very different. abs(x) is calling a global function, nothing to do with C.
RichieHindle
+11  A: 

The official answer from Guido van Rossum, with additional explanation from Fredrik Lundh, is here: http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm

In a nutshell:

  1. abs(x) reads more naturally than x.abs() for most such operations

  2. you know that abs(x) is getting an absolute value, whereas a method x.abs() could mean something different depending on the class of x.

RichieHindle
great read +1
ojblass
Once you heard it the second reason makes sooo much sense
Tobias
+1: quote the documentation.
S.Lott
A: 

Python is a language that supports object oriented coding, but it deliberately isn't a pure OO language. As you correctly mention, Python classes, even user defined ones, haven't always derived from a single base class.

Functions are the basic unit of functionality in Python, so it makes sense for the core operations (random sample: str, dir, print, hash) to look like functions.

James Hopkin