Why doc call `__init__` as a method rather than function?

Alan Gauld learn2program at gmail.com
Fri Sep 15 14:29:57 EDT 2023


On 15/09/2023 11:49, scruel tao via Python-list wrote:
> ```python
>>>> class A:
> ...   def __init__(self):
> ...     pass

> On many books and even the official documents, it seems that 
> many authors prefer to call `__init__` as a "method" rather 
> than a "function".

That' because in OOP terminology methods are traditionally
implemented as functions defined inside a class (There are
other ways to define methods in other languages, but the
class/function duology is by far the most common.)

What is a method? It is the way that an object handles a
message. OOP is all about objects sending messages to each
other. Many different objects can receive the same message
but they each have their own method of handling that message.
(This is called polymorphism.)

Over time the most common way to implememt OOP in a language
is to invent a "class" structure and to allow functions to
either be defined within it or added to it later. In either
case these functions are what define how a class (and its
object instances) handle a given message. So the function
describes the method for that message. And over time that
has become shortened to the function inside a class *is*
its method.

In practice, the message looks like a function call. And
the method consists of the function body (and/or any
inherited function body). Thus every method is a function
(or set of functions) but not every function is a  method
(or part of one).

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Python-list mailing list