On 15Sep2023 10:49, scruel tao <scru...@hotmail.com> wrote:
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".
The book PYTHON CRASH COURSE  mentioned that "A function that’s part of a class is a 
method.", however, ` A.__init__` tells that `__init__` is a function...

As mentioned, methods in Python _are_ functions for use with a class.

<function A.__init__ at 0x0000026CFC5CCEE0>
a = A()

<bound method A.__init__ of <__main__.A object at 0x0000026CFC1BB400>>
I wonder how can I call `__init__` as? Consider the output above.
Maybe both are OK?

As you can see, they're both legal expressions.

The thing about `__init__` is that it's usually called automatically which you make a new object. Try putting a `print()` call in your `__init__` method, then make a new instance of `A`.

The purpose of `__init__` is to initialise the object's attribute/state after the basic, empty-ish, object is made.

Like other dunder methods (methods named with double underscores front and back) it is called automatically for you. In a subclass the `__init__` method calls the subperclass `__init__` and then does whatever additional things might be wanted by the subclass.

Let's look at what you used above:

    >>> A.__init__
    <function A.__init__ at 0x0000026CFC5CCEE0>

Here's we've just got a reference to the function you supposlied with the class definition for class `A`.


    >>> a = A()
    >>> a.__init__
    <bound method A.__init__ of <__main__.A object at 0x0000026CFC1BB400>

Here's you've accessed the name `__init__` via an existing instance of `A`, your variable `a`. At this point you haven't called it. So you've got a callable thing which is a binding of the function to the object `a` i.e. when you call it, the "bound method" knows that t is associated with `a` and puts that in as the first argument (usually named `self`).

Cameron Simpson <c...@cskk.id.au>

Reply via email to