What is not objects in Python?

sjdevnull at yahoo.com sjdevnull at yahoo.com
Sun Sep 28 16:24:35 EDT 2008


On Sep 28, 2:29 pm, process <circularf... at gmail.com> wrote:
> I have heard some criticism about Python, that it is not fully object-
> oriented.
>
> What is not an object in Python?
>

Parts of the syntax aren't objects.  e.g. "=" or ":" aren't objects.

Unlike in some less fully OO-languages (e.g. Java or C++), classes,
functions, and many other "built-in language features" are objects in
Python.  You can do things like return functions just like any other
object, rather than having to do it indirectly through references or
some such:

>>> def add_n(x):
...    def rv(y):
...       return y + x
...    return rv
...
>>> add_2 = add_n(2)
>>> add_3 = add_n(3)
>>>
>>> print add_2(6)
8
>>> print add_2(10)
12
>>> print add_3(6)
9

> Why isn't len implemented as a str.len and list.len method instead of
> a len(list) function?

FWIW, it is implemented as a str.__len__ method (and list.__len__
method); the len() function just uses those internally.  Java and C++
have similar shortcuts for, say, "+" or "-".  But Python allows you to
call all the operators as methods if you want:

>>> 1+2
3
>>> (1).__add__(2)
3
>>> a_list = [ "a", "b", "c" ]
>>> len(a_list)
3
>>> a_list.__len__()
3


And, of course, the presence of the len() shortcut doesn't alter the
OO-nature of the language any more than the presence of the + operator
does in any OO language.  Derived classes' __len__ operators are
called correctly by len():

>>> class list_that_lies(list):
...     def __len__(self):
...         return 2
...
>>> bad_list=list_that_lies([1,2])
>>> print bad_list
[1, 2]
>>> len(bad_list)
2
>>> bad_list.append(3)
>>> print bad_list
[1, 2, 3]
>>> len(bad_list)
2




More information about the Python-list mailing list