[Python] Understand the self of the class. Learn the role of self from the execution result with or without self.

[Python] Understand the self of the class. Learn the role of self from the execution result with or without self.

Anyone who started python wondered, Content that is full of content everywhere.

Reorganize for yourself.


### ■ Summary -It is necessary to set one argument of the method in the class by default. └ Otherwise an error └ Use self habitually

・ Self is optional └ Works even if it is not self

-When using a variable in the class, use the self. Variable. └ If you use x = 123, "self.x"

・ Global variables can be used as they are in the class


### ■ Verification details

-[Difference in behavior with and without self](Difference in behavior with and without #self) ・ [It doesn't have to be self](It doesn't have to be #self) -[Differences inside and outside the def class](Differences inside and outside the #def class) -[Set arguments with methods in class](#Set arguments with methods in class) -[Use variables in class](# Use variables in class)


## Difference in operation with and without self Create the following class to see the difference in operation with and without self.

** ▼ Confirmation class **

class1


class class1:
    def method1(self):
        print("Executed method1")

x = class1()
x.method1()

#output
#Executed method1

** ▼ Without self **

No self


class class1:
    def method1():
        print("Executed method1")

x = class1()
x.method1()

#output
# TypeError: method1() takes 0 positional arguments but 1 was given

** ■ Error ** method1() takes 0 positional arguments but 1 was given

The method "method1" defined in the class does not take an argument (0), but 1 is given.

Even in the executed process, the inside of () is empty and no argument is entered. (Normally argument 0) x.method1()


** ■ Cause ** When executing a method in a class, the instance itself is automatically given as an argument.


Example
x.method1 () → Argument 1 x.method1 ('A','B') → Argument 3


** ■ Countermeasure ** The methods in the class must be given at least one argument by default.

⇛ Its argument is "self"

The argument may be other than self. It is customary to use self.


## It doesn't have to be self ** ▼ When using characters other than self **

When the argument self is replaced with "a" and "aiueo".

Characters other than self ①


class class1:
    def method1(a):
        print("Executed method1")

x = class1()
x.method1()

#output
#Executed method1

Characters other than self ②


class class1:
    def method1(AIUEO):
        print("Executed method1")

x = class1()
x.method1()

#output
#Executed method1

Both run without problems.


## Differences inside and outside the def class

If you bring the defined method out of the class, of course no arguments are passed by default.

Out of class


def method1():
    print("Executed method1")
    
method1()

#output
#Executed method1

The opposite of the method in the class, if you pass only one argument, you will get an error.

error


def method1():
    print("Executed method1")
    
method1('A')

#output
# TypeError: method1() takes 0 positional arguments but 1 was given

Error: method1 () takes 0 positional arguments but 1 was given

An error that there are 0 arguments but 1 extra.


## Set arguments with methods in the class

Since one argument is set by default in the class, when setting other arguments, it is necessary to set one more than usual. (Becomes self + α)

When setting arguments


class class2:
    def weather(self, day, sky):
        print(day + 'The weather is' + sky + 'is.')

x = class2()
x.weather('today', 'Sunny')

#output
#The weather is sunny today.

Set three arguments of the weather method in the class: "self", "day", and "sky".


** ▼ When "self" is changed to "a" ** Of course, it works normally even if it is not "self".

Other than self


class class2:
    def weather(a, day, sky):
        print(day + 'The weather is' + sky + 'is.')

x = class2()
x.weather('today', 'Sunny')

#output
#The weather is sunny today.

## Use variables in the class

The big advantage of a class is that you can set functions and variables that are valid only within the class. (Not global)

You need to combine it with "self" to use variables in the class.


** ▼ Use variables in the class **

To call the variable "x = 123" defined in the class in the method, it must be "self.x".

class3


class class3:
    x = 123

    def method1(self):
        print(self.x)

cls = class3()
cls.method1()  

#output
# 123

** ▼ If you do not add self **

If there is no self in "self.x", an error will occur.

x only


class class3:
    x = 123

    def method1(self):
        print(x)

cls = class3()
cls.method1()  

#output
# NameError: name 'x' is not defined

Error: name'x' is not defined "X = 123" in the class is not "x".


** ▼ Use global variables **

If you use a variable defined outside of class, you don't need self.

Use global variables


x = 123

class class3:

    def method1(self):
        print(x)

cls = class3()
cls.method1()

#output
# 123

By using self, you can clearly distinguish whether it is a global variable or a variable in a class.


** ▼ Other than self ** By the way, it works other than self.

Other than self


class class3:
    x = 123
    
    def method1(AIUEO):
        print(AIUEO.x)

cls = class3()
cls.method1()  

#output
# 123

I was wondering what self is, but I think it's convenient and necessary to know how to use it.

Recommended Posts

[Python] Understand the self of the class. Learn the role of self from the execution result with or without self.
Learn Nim with Python (from the beginning of the year).
Prepare the execution environment of Python3 with Docker
Why is the first argument of [Python] Class self?
Measure the execution result of the program in C ++, Java, Python.
Save the result of the life game as a gif with python
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
Learn the basics of Python ① Beginners
Hit a method of a class instance with the Python Bottle Web API
I tried to streamline the standard role of new employees with Python
The result of making the first thing that works with Python (image recognition)
[Python3] Understand the basics of Beautiful Soup
Learning notes from the beginning of Python 1
Check the existence of the file with python
[Python] Understand the content of error messages
The result of installing python in Anaconda
Learn the design pattern "Singleton" with Python
Intuitively learn the reshape of Python np
Python Note: The secret role of commas
Learning notes from the beginning of Python 2
Learn the design pattern "Facade" with Python
[Python3] Understand the basics of file operations
"Python AI programming" starting from 0 for windows
Business efficiency starting from scratch with Python
Generate a class from a string in Python
Python typing
Python explosive environment construction starting from zero (Mac)
Registering with PyPI from modern Python library self-made
[Python] class, instance
About python, class
Python dynamic typing
sql from python
[Python] Understand the self of the class. Learn the role of self from the execution result with or without self.
MeCab from Python
Python class, instance
#Python basics (class)
[Python] Django Source Code Reading View Starting from Zero ①
Introduction to Mathematics Starting with Python Study Memo Vol.1
How to pass the execution result of a shell command in a list in Python
You can call the method of the class directly in Python3 without adding @staticmethod
Deep Learning from scratch The theory and implementation of deep learning learned with Python Chapter 3
2016 The University of Tokyo Mathematics Solved with Python
View the result of geometry processing in Python
Calculate the total number of combinations with python
Check the date of the flag duty with Python
[Note] About the role of underscore "_" in Python
Extract only complete from the result of Trinity
Convert the character code of the file with Python3
From the introduction of pyethapp to the execution of contract
[Python] Determine the type of iris with SVM
From the initial state of CentOS8 to running php python perl ruby with nginx
Get the value of a specific key in a list from the dictionary type in the list with Python
Extract images and tables from pdf with python to reduce the burden of reporting
One of the cluster analysis methods, k-means, is executed with scikit-learn or implemented without scikit-learn.
I thought about why Python self is necessary with the feeling of a Python interpreter
Use data class for data storage of Python 3.7 or higher
Extract the table of image files with OneDrive & Python
The wall of changing the Django service from Python 2.7 to Python 3
Add the attribute of the object of the class with the for statement
The story of Python without increment and decrement operators.
I want to grep the execution result of strace
Find out the location of Python class definition files.
[Python] Get the text of the law from the e-GOV Law API
The first algorithm to learn with Python: FizzBuzz problem
Destroy the intermediate expression of the sweep method with Python
Study from the beginning of Python Hour1: Hello World
Visualize the range of interpolation and extrapolation with python
A python implementation of the Bayesian linear regression class
Get the return code of the Python script from bat
Calculate the regression coefficient of simple regression analysis with python
Get the result in dict format with Python psycopg2
Learn the design pattern "Chain of Responsibility" in Python
Preparing the execution environment of PyTorch with Docker November 2019
Reproduce the execution example of Chapter 4 of Hajipata in Python
Summary of the basic flow of machine learning with Python
14 quizzes to understand the surprisingly confusing scope of Python