Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why builtin functions instead of root class methods?

Tags:

python

oop

(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?

like image 646
Tobias Avatar asked Dec 23 '22 11:12

Tobias


2 Answers

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.

like image 58
RichieHindle Avatar answered Jan 08 '23 20:01

RichieHindle


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

like image 25
ojblass Avatar answered Jan 08 '23 22:01

ojblass