functions vs methods
sharan.basappa at gmail.com
Sun Jul 22 04:37:51 EDT 2018
On Sunday, 22 July 2018 13:32:16 UTC+5:30, Ben Finney wrote:
> Sharan Basappa <sharan.basappa at gmail.com> writes:
> > Is there a difference between functions and methods in Python.
> Python's documentation includes a useful Glossary. See the terms
> Every method is a function; but there are functions that are not
> What distinguishes a method is that it is associated with a specific
> class. A method is always a method *of* some class or object.
> > For example, this is the text from tutorialpoint on Python:
> > Python includes the following list functions - cmp, len etc.
> The functions ‘cmp’, ‘len’, are not associated with any particular
> class. They can be called without being bound to any object.
> > Python includes following list methods - append, count
> That means the functions it is referring to are each methods of ‘list’.
> Any instance of ‘list’ has methods ‘append’ and ‘count’, bound to that
> > In the first case, len is a function that python provides to which
> > list can be passed and in the second case, append is a method within
> > list class?
> Yes, that's correct.
> > If my interpretation is correct, why not make len also as a part of
> > list class itself?
> 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”, 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.
> Your particular question is itself a FAQ
> \ “All progress has resulted from people who took unpopular |
> `\ positions.” —Adlai Stevenson |
> _o__) |
> Ben Finney
More information about the Python-list