Hacker News new | ask | show | jobs
by xapata 3577 days ago
You can find explanations for both those questions in the design FAQ.

The explicit self came from Modula-3. https://docs.python.org/2/faq/design.html#why-must-self-be-u...

The explanation for len is a little lacking. https://docs.python.org/2/faq/design.html#why-does-python-us...

Guido once explained further in an email to the mailing list. I've forgotten some of it, but the gist is that he didn't want anyone to accidentally create or override a .len() method to do something other than tell the number of elements in the container.

And... almost everything is a method. Even ``len(obj)`` is just sugar for ``obj.__len__()``.

1 comments

almost everything is a method

Not "almost". Just "everything is a method", in terms of function calls. Even user-defined standalone functions. Consider:

    def my_func(arg):
        return arg + 5
The following are equivalent, and show how things work:

    my_func(3)
and

    my_func.__call__(3)
and

    types.FunctionType.__call__(my_func, 3)
I'm not certain, but I think the C API can avoid that. I've learned to say "almost" because every time I say Python can't X, someone shows me it can.
There are a few functions in the C API to let you call things, depending on the type of thing and set of arguments you feel like providing, and they rely on the Python API to handle the calling for you. I imagine if you really wanted to, and knew enough about the structure and expectations of the Python object you were working with, you could "manually" call without going through one of those C API functions, but I don't know that I'd recommend trying it...