Try to understand Python self

Notice

I'm just starting out with Python and I'm full of things I don't understand. (I'm sorry if this article is also wrong) It's almost my memorial article.

Introduction

When studying classes in Python, self comes up. However, it seems like a magic, so I'm not sure, so I will summarize what I investigated.

This whole code

main.py


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

    def naku(self):
        print("Meow")

tama = Cat("Tama")
tama.naku()

Cat.naku(tama)

Before getting into the main subject

In python

main.py


receiver.Method(argument…)

,

main.py


Receiver class.Method(receiver,argument…)

Interpret as. I don't know why. (really sorry) However, it works the same regardless of which one you write, and when you understand self, it is easier to understand the former as the latter, so I will explain it in that way.

Main subject

For now, let's take a step-by-step look at the entire code. First, there is the Cat class.

main.py


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

    def naku(self):
        print("Meow")

There is a name in the instance variable, The naku function sounds "Nya".

Since a class is like a concept, it is actually summoned (instantiated) with the name "Tama".

main.py


tama = Cat("Tama")

Yes, this has summoned the cat Tama-chan. Next, let me ring.

main.py


#receiver.Method(argument…)
tama.naku() #=>Meow

Yes, it screamed. This is another way of writing, isn't it?

main.py


#Receiver class.Method(receiver,argument…)
Cat.naku(tama) #=>Meow

Yes, what you want to see here is that "tama" is in the receiver part of the argument parentheses. So, if you compare it with the naku function defined in the class again,

python


#neko function definition
def naku(self):

#Function call
Cat.naku(tama)

The arguments matched. This is the true identity of self.

In other words, here it is "tama = self". It is often explained that "self is the instance itself", but simply because the function called "receiver class.method (receiver, argument ...)" is called in the python grammar, the first It seems that it is useless because the number of arguments does not match unless the instance itself is put in one argument (receiver).

The same is true for the init function. Considering the operation of the init function called when summoning Tama-chan,

python


#Receiver class.Method(receiver,argument…)
Cat.__init__(tama,"Tama")

You can understand that the code is done internally.

No, why did the "tama" argument of Cat () become the argument of the init function! ?? That's a question that certainly comes up, but if you think about it carefully, the init function is a special one that is always called at the time of instantiation, unlike the function you define yourself, so it is taken as an argument of Cat (). However, I think that it is automatically included in the argument of the init function. (Please let me know if anyone knows.) Besides, classes are not functions, so they don't need arguments.

What I found

--self is just an argument --Internally called by "receiver class.method (receiver, argument)" ――You can manage without worrying about it ――The sentences I write are long! !!

Recommended Posts

Try to understand Python self
Try python
Try to operate Facebook with Python
Try to calculate Trace in Python
Try converting cloudmonkey CLI to python3 -1
Try to reproduce color film with Python
Try logging in to qiita with Python
Python> try: / except:
Try to operate Excel using Python (Xlwings)
[Python] Pandas to fully understand in 10 minutes
Python amateurs try to summarize the list ①
[Python] Understand how to use recursive functions
Understanding python self
Try to implement and understand the segment tree step by step (python)
A way to understand Python duck typing
"Backport" to python 2
First steps to try Google CloudVision in Python
Try to implement Oni Maitsuji Miserable in python
Try auto to automatically price Enums in Python 3.6
Try to solve the Python class inheritance problem
Let's understand how to pass arguments (Python version)
Try to solve the man-machine chart with Python
Try to draw a life curve with python
Try to make a "cryptanalysis" cipher with Python
Try to automatically generate Python documents with Sphinx
Try to calculate RPN in Python (for beginners)
Python mock to try AWS IoT Device Shadow
Try to make a dihedral group with Python
Knowledge notes needed to understand the Python framework
Try to detect fish with python + OpenCV2.4 (unfinished)
Understand Python for Pepper development. -Introduction to Python Box-
Try scraping with Python.
How to install Python
python try ~ except ~ else
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
Rewrite Python2 code to Python3 (2to3)
How to install python
python decorator to retry
Introduction to Python language
Introduction to OpenCV (python)-(2)
Try Debian + Python 3.4 + django1.7 ...
Try to implement yolact
Try gRPC in Python
Note to daemonize python
Introducing Python 2.7 to CentOS 6.6
Connect python to mysql
Try 9 slices in Python
[Python MinMaxScaler] Normalize to 0 ~ 1
Try using Tweepy [Python2.7]
Python try / except notes
Even beginners want to say "I fully understand Python"
Try to solve the programming challenge book with python3
[First API] Try to get Qiita articles with Python
Python beginners try adding basic auth to Django admin
Try to make a Python module in C language
[Python] Try to read the cool answer to the FizzBuzz problem
Try to make a command standby tool with python
Try to improve your own intro quiz in Python
(Python) Try to develop a web application using Django
Try to solve the internship assignment problem with Python