Why does Python mix OO concepts and non OO concepts for operation s on basic types?

Chris Liechti cliechti at gmx.net
Wed May 22 19:25:06 EDT 2002


"Michael P. Soulier" <msoulier at mcss.mcmaster.ca_.nospam> wrote in
news:ach7s6$c88$1 at news.storm.ca: 

> On 23 May 2002 00:01:17 +0200, Chris Liechti <cliechti at gmx.net> wrote:
>>  
>> think abbout it as an operator. its is written in function syntax
>> because +-*/% etc are aleady used.
>> 
>> it has some advantages and it isn't "inconsistent" at all. i think
>> you do prefer to write 
>>>>> 1 + 2
>> instead of
>>>>> 1 .__add__(2)
>> don't you?
>> (with or without underlines. apropos, "range(3).__len__()" works ;-)
> 
>     Actually, one of the few things I like about Ruby is that all
>     objects in 
> Ruby do have methods, and thus to add two numbers...
> 
>     2 + 4
>     2.+(4)

doesn't looks very readable to me, if thats realy calling the method 
directly, not using the operator. at least i would expect that this is 
adding the float 2.0 to an integer 4 which is in arithmetical braces which 
just do nothing here. i.e. you can write that in python:
>>> 2.+(4)
6.0
the result is a float, but
>>> 2 .__add__(4) 
6
(note the space betwen 2 and the dot) now its an integer result.

pythons way to write special methods with underlines "__add__" etc. makes 
it very readble IMHO. and relaively easy to explain.
 
>     are equivalent. 
> 
>     Python _does_ seem mildly inconsistent in this regard. Giving
>     strings 
> methods helped a bit, but tuples still have none, and neither do
> numbers. 
> 
>>>> dir(())
> []
>>>> dir(2)
> []

well both have methods... "dir" is just not telling you everything you 
expect. most methods belong to the class and not to the instance (you can 
have such but they're rare). this means that the code for methods only 
needs to be once in the memory and not mutiple times for each instance.

>>> dir(1 .__class__)
['__abs__', '__add__'...., '__xor__']
>>> len(dir(().__class__))
23
>>> (1,2,3).__getitem__(1)
2


>     IMHO, they should all be objects with methods and a class, such
>     that they may be subclassed. 

they are, in 2.2+

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list