functions vs methods

Chris Angelico rosuav at gmail.com
Sun Jul 22 16:09:24 EDT 2018


On Mon, Jul 23, 2018 at 1:49 AM, MRAB <python at mrabarnett.plus.com> wrote:
> On 2018-07-22 10:08, Ben Finney wrote:
>>
>> INADA Naoki <songofacandy at gmail.com> writes:
>>
>>> Please don't refer the FAQ entry.
>>> See this: https://bugs.python.org/issue27671
>>
>>
>> Interesting. Thanks for raising that bug report.
>>
>> I offer my text as a starting point for a better explanation:
>>
>>      Because ‘len’ works with *any* sequence, not only lists. To
>>      implement it as a method of each sequence type, it would have to be
>>      implemented on each type separately, which is a design that is
>>      needlessly more complex.
>>
>>      This is common in Python: it uses so-called “duck typing”
>>      <URL:https://docs.python.org/3/glossary.html#term-duck-typing>,
>>      where the way an object behaves is more important than its type.
>>      Because “what is the length of this object” is a question valid for
>>      a broad variety of types, the design decision was made to allow it
>>      to accept any type for which that query makes sense.
>>
>> Feel free to use that (or something derived from it) to improve the
>> documentation as you suggest.
>>
> Doesn't it have to be implemented on each type anyway?

Not always. If you have an actual protocol like __len__, then yes, but
there are many protocols that cover multiple functions. For instance,
once you define __add__, you can perform addition with your object -
both "x + 1" and "1 + x", and even "x += 1". And once you define
__iter__, all manner of things suddenly start working. (That's
probably the biggest one.)

ChrisA



More information about the Python-list mailing list