I want to clear up the question of the "__init__" method and the "self" argument of a Python class.

Summary of this article

This article is intended to be as intuitive as possible for those who write "def \ _ \ _ init \ _ \ _ (self):" that appears in Python class definitions as if they were memorized for the time being. I wrote it to do.

Python class definition

Python takes the following format when defining a class.

class demo_class():
    def __init__(self):
        pass

Since this is not intuitive (for python), I think that there are many beginners other than myself who are struggling.

Explanations such as reference books (Introduction to Python 3)

\ _ \ _ Init \ _ \ _ () is a special name given to the method that initializes an individual object when it is created from the class definition.

Well, I'm not sure if you say that much. However, this introductory Python 3 continued to explain what the Python processing system does, and it was easy to understand, so I will summarize it and explain it with additional figures.

To make it easier to explain, add the member variable name of the class and add the element to add "hoge".


class demo_class():
    def __init__(self,name):
        self.name = name

a = demo_class("hoge")
print("a: ",a)
print("a.name: ",a.name)


[Output result]

a:  <__main__.demo_class object at 0x1023b6668>
a.name:  hoge

Image of how Python classes behave

Python can instantiate a class just like executing a function. An instance is an entity of an object, and instantiation roughly means making a program executable in memory.

In fact, where does the python interpreter run from in the line below?

a = demo_class("hoge")
  1. Refer to the definition of demo_class class
  2. Create an empty object of demo_class class
  3. Initialize the demo_class class object based on the argument
  4. Assign "hoge" of string to member variable name
  5. Name the object a

It will be processed in the above order. It looks like the figure below obj.dot.png

obj.dot.png

obj.dot.png

Explanation of the figure

First of all, create an empty class object from the class definition

obj.dot.png

The generated class object has to modify the previous object in order to initialize itself (add "hoge" to the name member). At this time, the python interpreter does not know what kind of initialization should be done to which object, and does not know how to refer to the variable.

The \ _ \ _ init \ _ \ _ method is a special method for initialization.

That is, ** to make it clear which object you want the Python interpreter to initialize and how ** to the special method \ _ \ _ init \ _ \ _ method for initialization ** the empty object you just created Is passed as a self argument **.

obj.dot.png

This allows you to identify your own objects and eliminates the need to create extra names for each class.

The problem here is "self.name".


def __init__(self,name):
    self.name = name

"Self.name" on the left side ** defines a member variable **, so ** create a name variable in the object and assign the name containing the argument "hoge" ** That is. In other words, ** the name on the first line and the name on the right side of the second line represent different things **. Since this is the same place, I think it's hard to understand at first glance.

The reason for the premise of "self." Is that it makes it explicit which object the interpreter should refer to for processing. (maybe)

(In python, anything that follows a "." Is called an attribute.)

obj.dot.png

Caution

In this article, there are many parts that are asserted as "to do XX" or "to do XX" and explained as a means for a limited purpose, but this is to grasp the image. This is the method taken to make it the first goal, and there are some problems in view of the long learning span.

reference

Getting Started Python3 Official documentation

Recommended Posts

I want to clear up the question of the "__init__" method and the "self" argument of a Python class.
I want to know the features of Python and pip
I want to explain the abstract class (ABCmeta) of Python in detail.
Python: I want to measure the processing time of a function neatly
Why is the first argument of [Python] Class self?
Don't take an instance of a Python exception class directly as an argument to the exception class!
How to use the __call__ method in a Python class
I want to start a lot of processes from python
I want to get the name of the function / method being executed
[Introduction to Python] I compared the naming conventions of C # and Python.
I want to output the beginning of the next month with Python
I want to use both key and value of Python iterator
I wrote AWS Lambda, and I was a little addicted to the default value of Python arguments
I want to extract the tag information (title and artist) of a music file (flac, wav).
I want to build a Python environment
(Python Selenium) I want to check the settings of the download destination of WebDriver
I want to batch convert the result of "string" .split () in Python
Hit a method of a class instance with the Python Bottle Web API
I want to color a part of an Excel string in Python
I tried to verify and analyze the acceleration of Python by Cython
I want to analyze the emotions of people who want to meet and tremble
I made a program to check the size of a file in Python
I want to make a web application using React and Python flask
I made a function to see the movement of a two-dimensional array (Python)
I want to pass an argument to a python function and execute it from PHP on a web server
I want to create a window in Python
I want to make a game with Python
I wrote a class in Python3 and Java
I want to customize the appearance of zabbix
About the * (asterisk) argument of python (and itertools.starmap)
A discussion of the strengths and weaknesses of Python
I want to write to a file with Python
I want to display the progress in Python!
The story of IPv6 address that I want to keep at a minimum
I want to use Python in the environment of pyenv + pipenv on Windows 10
I want to set a life cycle in the task definition of ECS
I want to add silence to the beginning of a wav file for 1 second
I want to exe and distribute a program that resizes images Python3 + pyinstaller
I want to see a list of WebDAV files in the Requests module
I want to crop the image along the contour instead of the rectangle [python OpenCV]
I made a tool to automatically back up the metadata of the Salesforce organization
Python program is slow! I want to speed up! In such a case ...
I want to get the file name, line number, and function name in Python 3.4
I made a script to record the active window using win32gui of Python
I want to output a path diagram of distributed covariance structure analysis (SEM) by linking Python and R.
If you define a method in a Ruby class and define a method in it, it becomes a method of the original class.
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I want to iterate a Python generator many times
I want to generate a UUID quickly (memorandum) ~ Python ~
I tried to notify the update of "Become a novelist" using "IFTTT" and "Become a novelist API"
I want to handle optimization with python and cplex
I want to write in Python! (2) Let's write a test
[Python] I made a system to introduce "recipes I really want" from the recipe site!
The story of Linux that I want to teach myself half a year ago
I tried to automate the article update of Livedoor blog with Python and selenium.
I want to randomly sample a file in Python
I want to inherit to the back with python dataclass
I want to fully understand the basics of Bokeh
I want to work with a robot in python.
I want to take a screenshot of the site on Docker using any font