On Sunday, 22 July 2018 13:32:16 UTC+5:30, Ben Finney wrote: > Sharan Basappa <sharan.basa...@gmail.com> writes: > > > Is there a difference between functions and methods in Python. > > Python's documentation includes a useful Glossary. See the terms > <URL:https://docs.python.org/3/glossary.html#term-method> > <URL:https://docs.python.org/3/glossary.html#term-function>. > > Every method is a function; but there are functions that are not > methods. > > 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 > instance. > > > 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. > > <URL:https://docs.python.org/3/glossary.html#term-duck-typing> > > Your particular question is itself a FAQ > <URL:https://docs.python.org/3/faq/design.html#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list>. > > -- > \ “All progress has resulted from people who took unpopular | > `\ positions.” —Adlai Stevenson | > _o__) | > Ben Finney
Thanks, Ben -- https://mail.python.org/mailman/listinfo/python-list